﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Appkiz.Apps.Workflow.Library;
using System.Xml;
using Appkiz.Library.Security.Authentication;
using Appkiz.Library.Security;
using Tiger.Common;
using System.Text;
using Newtonsoft.Json;
using Tiger.Models;
using Appkiz.Library.Common;

namespace Tiger.Controllers
{
    public class WorkflowController : Controller
    {
        /*
         * 全局变量
         */
        // 数据库上下文
        WhDbContext whdb = new WhDbContext();

        #region 获取领导意见列表，按照【排序】由大到小(PC端用)
        /// <summary>
        /// 获取领导意见列表，按照【排序】由大到小(PC端用)
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            /*
             * 变量定义
             */
            // 工作流管理
            WorkflowMgr mgr = new WorkflowMgr();
            // 组织人员管理
            OrgMgr orgMgr = new OrgMgr();
            // 排序
            var Order = string.Empty;

            var employee = (User.Identity as AppkizIdentity).Employee;

            /*
             * 参数获取
             */
            // 消息ID
            var MessageID = Request.Params["MessageID"];

            /*
             * 参数校验
             */
            // 消息ID
            if(string.IsNullOrEmpty(MessageID))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "消息ID不能为空"
                });
            }
            /*
             * 获取当前消息
             */
            var message = mgr.GetMessage(MessageID);
            if (message == null)
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "流程不存在"
                });
            }
            var NodeKey = string.Empty;
            if(message.FromTemplate == WHConstants.Workflow_Read_MessageID)
            {
                Order = "DESC";

                NodeKey = WHConstants.Workflow_Read_Leader_Node;
            }
            else if(message.FromTemplate == WHConstants.Workflow_XiaJi_MessageID)
            {
                Order = "ASC";
                NodeKey = WHConstants.Workflow_XiaJi_Leader_Node;
            }
            else if(message.FromTemplate == WHConstants.Workflow_ShangJi_MessageID)
            {
                Order = "DESC";
                NodeKey = WHConstants.Workflow_ShangJi_Leader_Node;
            }
            else
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "流程类型不支持"
                });
            }
            // 是否可以修改按钮
            var canChaneOpinion = WorkflowUtil.CanChangeOpinion(MessageID, employee);

            /*
             * 流程记录查询与排序
             */
            // 新意见列表
            var newOpinionList = whdb.NewOpinion.Where(n => n.MessageID == MessageID && n.NodeKey == NodeKey).OrderBy(n => n.order).ToList();

            Doc doc = mgr.GetDocByWorksheetID(mgr.GetDocHelperIdByMessageId(MessageID));
            Worksheet worksheet = doc.Worksheet;
            Workcell workcell = worksheet.GetWorkcell(10, 4);
            XmlNodeList history = workcell.History;
            Dictionary<string, string> dict = new Dictionary<string, string>();
            List<KeyValuePair<string, string>> itemList = new List<KeyValuePair<string, string>>();
            List<string> list = new List<string>();

            //Dictionary<string, TGR_NewOpinion> resultDict = new Dictionary<string, TGR_NewOpinion>();

            //foreach(TGR_NewOpinion newOpinion in newOpinionList)
            //{
            //    if (resultDict.Keys.Contains(newOpinion.EmplID))
            //    {
            //        if(newOpinion.UpdatedTime > resultDict[newOpinion.EmplID].UpdatedTime)
            //        {
            //            resultDict[newOpinion.EmplID] = newOpinion;
            //        }
            //    }
            //    else
            //    {
            //        resultDict[newOpinion.EmplID] = newOpinion;
            //    }
            //}
            //List<TGR_NewOpinion> resultOpinionList = new List<TGR_NewOpinion>();
            //foreach(KeyValuePair<string, TGR_NewOpinion> item in resultDict)
            //{
            //    resultOpinionList.Add(item.Value);
            //}
            //var resultOpinionList = newOpinionList;
            // 每个用户对应签批数量
            var nodeDict = new Dictionary<string, int>();
            // 排序(默认从1开始)
            var nodeOrderDict = new Dictionary<string, int>();

            foreach(XmlNode node in history)
            {
                var emplId = node.Attributes.GetNamedItem("emplId").InnerText;
                // 更新排序
                if (nodeDict.ContainsKey(emplId))
                {
                    int order = nodeDict[emplId];
                    nodeDict[emplId] = order + 1;
                }
                else
                {
                    nodeDict.Add(emplId, 1);
                }
            }

            foreach (XmlNode node in history)
            {
                var emplId = node.Attributes.GetNamedItem("emplId").InnerText;
                var value = node.Attributes.GetNamedItem("Value").InnerText;
                var updateTime = node.Attributes.GetNamedItem("UpdateTime").InnerText;

                // 更新排序
                if(nodeOrderDict.ContainsKey(emplId))
                {
                    int order = nodeOrderDict[emplId];
                    nodeOrderDict[emplId] = order + 1;
                }
                else
                {
                    nodeOrderDict.Add(emplId, 1);
                }
                var currentClass = "";
                var editIcon = string.Empty;
                var orderString = string.Empty;
                // 查找是否有对应的新意见，使用新意见替换旧意见
                foreach(TGR_NewOpinion newOpinion in newOpinionList)
                {
                    // 同一个人的意见，且顺序相同就替换对应的签批意见
                    if(newOpinion.EmplID == emplId && nodeOrderDict[emplId] == newOpinion.order)
                    {
                        value = newOpinion.Opinion;
                        updateTime = newOpinion.UpdatedTime.Value.ToString("yyyy-%M-dd HH:mm");
                        orderString = Convert.ToString(newOpinion.order);
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
                // 如果是当前用户，且是最后一条记录，则设置可修改
                // 流程未结束，可以修改的情况下才可以修改
                if (emplId == employee.EmplID && nodeDict[emplId] == nodeOrderDict[emplId] && canChaneOpinion == true)
                {
                    currentClass = "my-opinion";
                    editIcon = "fa fa-edit";
                }

                itemList.Add(new KeyValuePair<string, string>(emplId, "<div class=\"history - item "+currentClass+"\" order=\""+ orderString+"\"><div class=\"history-people\">{0}(" + updateTime + "):</div><span style=\"word-wrap: break-word;\">" + value + "</span><i class=\""+editIcon+"\" style=\"margin-left:8px\"></i></div>"));
                list.Add(emplId);
            }

            if(list.Count > 0)
            {
                var sql = @"SELECT EmplID, EmplName FROM ORG_Employee WHERE EmplID IN ({0}) ORDER BY GlobalSortNo " + Order;
                var results = DbUtil.ExcuteSqlCommand(string.Format(sql, string.Join(",", list)), DbUtil.WKF_GlobalSortNo);
                Dictionary<string, string> orderredDict = (Dictionary<string, string>)results.ElementAt(0);
                StringBuilder sb = new StringBuilder();

                foreach (KeyValuePair<string, string> item in orderredDict)
                {
                    foreach(KeyValuePair<string, string> innerItem in itemList)
                    {
                        if(innerItem.Key == item.Key)
                        {
                            sb.Append(string.Format(innerItem.Value, item.Value));
                        }
                    }
                }

                return new JsonNetResult(new
                {
                    history = sb.ToString()
                });
            }
            else
            {
                return new JsonNetResult(new
                {
                    history = ""
                });
            }
        }
        #endregion

        #region 获取部门意见列表，需要筛选(PC端用)
        /// <summary>
        /// 获取部门意见列表，需要筛选(PC端用)
        /// </summary>
        /// <returns></returns>
        public ActionResult DeptHistory()
        {
            /*
             * 参数获取
             */
            // 角色名称
            var RoleName = Request.Params["RoleName"];
            // 工作流ID
            var MessageID = Request.Params["MessageID"];

            /*
             * 参数校验
             */
            // 角色名称
            if (string.IsNullOrEmpty(RoleName))
            {
                return ResponseUtil.Error(400, "角色名称不能为空");
            }
            // 工作流ID
            if(string.IsNullOrEmpty(MessageID))
            {
                return ResponseUtil.Error(400, "工作流ID不能为空");
            }

            /*
             * 获取角色内所有成员
             */
            var sql = string.Format(@"SELECT * FROM ORG_EmplRole JOIN ORG_Role ON ORG_Role.RoleName = '{0}' AND ORG_EmplRole.RoleID = ORG_Role.RoleID", RoleName);
            var EmployeeList = DbUtil.ExcuteSqlCommand(sql, DbUtil.WKF_EmployeeList);

            var EmplIDList = new List<string>();
            foreach(var emplID in EmployeeList)
            {
                EmplIDList.Add(emplID.ToString());
            }
            /*
             * 获取所有人的评论
             */
            WorkflowMgr mgr = new WorkflowMgr();
            OrgMgr orgMgr = new OrgMgr();
            Doc doc = mgr.GetDocByWorksheetID(mgr.GetDocHelperIdByMessageId(MessageID));
            Worksheet worksheet = doc.Worksheet;
            Workcell workcell = worksheet.GetWorkcell(12, 4);
            XmlNodeList history = workcell.History;
            //Dictionary<string, string> dict = new Dictionary<string, string>();
            List<string> list = new List<string>();

            StringBuilder sb = new StringBuilder();

            foreach (XmlNode node in history)
            {
                var emplId = node.Attributes.GetNamedItem("emplId").InnerText;
                var value = node.Attributes.GetNamedItem("Value").InnerText;
                var updateTime = node.Attributes.GetNamedItem("UpdateTime").InnerText;

                //dict.Add(emplId, "<div class=\"history - item\"><div class=\"history-people\">{0}(" + updateTime + "):</div>" + value + "</div>");
                // 不在角色内，且评论为【已阅】的人，不予显示
                if (!EmplIDList.Contains(emplId) && value != null && value.Trim() == "已阅") {
                    continue;
                } else
                {
                    var employee = orgMgr.GetEmployee(emplId);
                    if (employee != null) {
                        sb.Append("<div class=\"history - item\"><div class=\"history-people\">" + employee.EmplName +"(" + updateTime + "):</div>" + value + "</div>");
                    }
                }
            }

            return new JsonNetResult(new
            {
                history = sb.ToString()
            });
        }
        #endregion

        #region 获得工作流下一个节点是谁(PC手机通用)
        /// <summary>
        /// 获得工作流下一个节点是谁(PC手机通用)
        /// </summary>
        /// <returns></returns>
        public ActionResult MessageHandle()
        {
            var MessageID = Request.Params["MessageID"];
            var NodeKey = Request.Params["NodeKey"];
            var FromNodeKey = Request.Params["FromNodeKey"];
            WorkflowMgr mgr = new WorkflowMgr();
            List<Employee> employees = mgr.ListPossibleHandlers(MessageID, NodeKey, FromNodeKey, System.Web.HttpContext.Current);
            var employee = employees.ElementAt(0);
            return new JsonNetResult(new
            {
                Succeed = true,
                Data = new
                {
                    empl = employee.EmplID
                }
            });
        }
        #endregion

        #region 获取工作流详情
        [HttpGet]
        public ActionResult GetDetailInfo(string mid)
        {
            var sqlTemp = string.Format(@"select FromTemplate,MessageTypeKey from WKF_Message where MessageID = '{0}'", mid);
            var tempInfo = DbUtil.ExcuteSqlCommand(sqlTemp, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
            var tempInfoDic = ((Dictionary<string, string>)tempInfo).FirstOrDefault();
            var MessageTypeKey = tempInfoDic.Key;
            var employee = (User.Identity as AppkizIdentity).Employee;

            #region 阅件
            if (MessageTypeKey == WHConstants.Workflow_Read_MessageID)
            {
                var MessageID = mid;
                WorkflowMgr mgr = new WorkflowMgr();
                OrgMgr orgMgr = new OrgMgr();
                Doc doc = mgr.GetDocByWorksheetID(mgr.GetDocHelperIdByMessageId(MessageID));
                Worksheet worksheet = doc.Worksheet;
                Message message = mgr.GetMessage(mid);

                //公文标题
                var documentTitle = worksheet.GetWorkcell(6, 4);
                var documentTitleName = documentTitle != null ? documentTitle.WorkcellValue : null;

                //WKF_WorkflowHistory
                //var nodeSql = string.Format(@"select CONVERT( nvarchar(50), WH_ID),NodeKey from WKF_WorkflowHistory where MessageID = '{0}'  order by HandledTime DESC", mid);
                //var nodeInfo = DbUtil.ExcuteSqlCommand(nodeSql, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
                //var nodeInfoDic = ((Dictionary<string, string>)nodeInfo).FirstOrDefault();
                //var nodeKey = nodeInfoDic.Value;
                var nodeKey = "";
                List<Node> source = mgr.ListNodeToBeHandle(employee.EmplID, "");
                foreach(Node node in source)
                {
                    if(node.MessageID == mid)
                    {
                        // 判断是否是传阅节点
                        if (node.NodeKey.StartsWith(WHConstants.Transfer_Node_Key_Header))
                        {
                            // node状态
                            node.NodeStatus = 3;
                            mgr.UpdateNode(node);
                            // 将Messagehandle中该数据清除掉
                            mgr.DelMessageHandle(mid, node.NodeKey, employee.EmplID);
                            // 添加到WorkflowHistory
                            var workflowHistory = new WorkflowHistory();
                            workflowHistory.MessageID = mid;
                            workflowHistory.NodeName = "(转发传阅)";
                            workflowHistory.NodeKey = node.NodeKey;
                            workflowHistory.HandledBy = employee.EmplID;
                            workflowHistory.HandledTime = DateTime.Now;
                            workflowHistory.ProcType = 3;
                            mgr.AddWorkflowHistory(workflowHistory);
                            continue;
                        }
                        else
                        {
                            nodeKey = node.NodeKey;
                            break;
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                //附件信息
                var workcellFile = worksheet.GetWorkcell(7, 4);
                var fileValue = workcellFile != null ? workcellFile.WorkcellValue : null;
                var fileInternalValue = workcellFile != null ? workcellFile.WorkcellInternalValue : null;
                var fileInternalValues = fileInternalValue.Split(';');
                var fileInternalValueList = new List<object>();
                if (!string.IsNullOrWhiteSpace(fileInternalValues.FirstOrDefault()))
                {
                    for (int i = 0; i < fileInternalValues.Count(); i++)
                    {
                        var info = string.Format(@"Apps/Workflow/Running/ShowPreview/{0}", fileInternalValues[i]);
                        var fileSql = string.Format(@"select AttFileName,AttExtension from WKF_WorkflowAttachment where AttID = '{0}'", fileInternalValues[i]);
                        var fileResults = DbUtil.ExcuteSqlCommand(fileSql, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
                        Dictionary<string, string> dict = new Dictionary<string, string>();
                        Dictionary<string, string> fileInfo = (Dictionary<string, string>)fileResults;
                        var attFileName = string.Empty;
                        var attExtension = string.Empty;
                        if (!string.IsNullOrWhiteSpace(fileInfo.ToString()))
                        {
                            attFileName = fileInfo.FirstOrDefault().Key;
                            attExtension = fileInfo.FirstOrDefault().Value;
                        }
                        fileInternalValueList.Add(new
                        {
                            AttId = fileInternalValues[i],
                            AttFileName = attFileName
                        });
                    }
                }
                // TODO: 部门附件列表
                var detpAttachments = new List<object>();
                var deptCellFile = worksheet.GetWorkcell(14, 4);
                var deptFileValue = deptCellFile != null ? deptCellFile.WorkcellValue : null;
                if(deptFileValue != null)
                {
                    var deptFileInternalValue = deptCellFile != null ? deptCellFile.WorkcellInternalValue : null;
                    var deptFileInternalValues = deptFileInternalValue.Split(';');
                    if (!string.IsNullOrWhiteSpace(deptFileInternalValues.FirstOrDefault()))
                    {
                        for (int i = 0; i < deptFileInternalValues.Count(); i++)
                        {
                            var info = string.Format(@"Apps/Workflow/Running/ShowPreview/{0}", deptFileInternalValues[i]);
                            var fileSql = string.Format(@"select AttFileName,AttExtension from WKF_WorkflowAttachment where AttID = '{0}'", deptFileInternalValues[i]);
                            var fileResults = DbUtil.ExcuteSqlCommand(fileSql, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
                            Dictionary<string, string> dict = new Dictionary<string, string>();
                            Dictionary<string, string> fileInfo = (Dictionary<string, string>)fileResults;
                            var attFileName = string.Empty;
                            var attExtension = string.Empty;
                            if (!string.IsNullOrWhiteSpace(fileInfo.ToString()))
                            {
                                attFileName = fileInfo.FirstOrDefault().Key;
                                attExtension = fileInfo.FirstOrDefault().Value;
                            }
                            detpAttachments.Add(new
                            {
                                AttId = deptFileInternalValues[i],
                                AttFileName = attFileName,
                                DeptName = ""
                            });
                        }
                    }
                }
                
                //审批信息
                var approveInfo = new
                {
                    FileInfo = new
                    {
                        FileValue = fileValue,
                        FileInternalValue = fileInternalValue,
                        FileInternalValueList = fileInternalValueList
                    }
                };
                // 是否可以编辑领导意见
                var canChaneOpinion = WorkflowUtil.CanChangeOpinion(mid, employee);
                Dictionary<string, string> resultDict = new Dictionary<string, string>();
                // 返回历史领导节点
                if (canChaneOpinion)
                {
                    nodeKey = WHConstants.Workflow_Read_Leader_Node;
                    resultDict = WorkflowUtil.GetLatestOpinion(mid, nodeKey, employee);
                }
                // 流程控制信息
                var control = new Dictionary<string, object>()
                {
                    {"NODE0002", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 },
                                    {"targetNodeKey", "" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", true },
                                    {"col", 4 },
                                    {"row", 8 }
                                }},
                                {"saveCell", new List<object>() {
                                    new Dictionary<string, object>()
                                    {
                                        {"type", "name" }, { "row", 9 }, {"col", 5 } 
                                    },
                                    new Dictionary<string, object>()
                                    {
                                        {"type", "date" }, { "row", 9 }, {"col", 8 }
                                    }
                                }}
                            }
                    },
                    {"NODE0003", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 },
                                    {"targetNodeKey", "" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 }
                                }}
                            }
                    },
                    {"NODE0004", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", true },
                                    {"col", 4 },
                                    {"row", 10 },
                                    {"targetNodeKey", "NODE0003" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", true },
                                    {"col", 4 },
                                    {"row", 10 }
                                }}
                            }
                    },
                    {"NODE0005", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", true },
                                    {"col", 4 },
                                    {"row", 12 },
                                    {"targetNodeKey", "NODE0003" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", true },
                                    {"col", 4 },
                                    {"row", 12 }
                                }}
                            }
                    },
                    //{"NODE0006", new Dictionary<string, object>(){
                    //            {"showReadedButton", new Dictionary<string, object>() {
                    //                {"show", false },
                    //                {"col", 0 },
                    //                {"row", 0 },
                    //                {"targetNodeKey", "" }
                    //            } },
                    //            {"needOpinion", new Dictionary<string, object>() {
                    //                {"show", false },
                    //                {"col", 0 },
                    //                {"row", 0 }
                    //            }}
                    //        }
                    //},
                    {"NODE0007", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 },
                                    {"targetNodeKey", "" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 }
                                }}
                            }
                    },
                    //{"NODE0008", new Dictionary<string, object>(){
                    //            {"showReadedButton", new Dictionary<string, object>() {
                    //                {"show", false },
                    //                {"col", 0 },
                    //                {"row", 0 },
                    //                {"targetNodeKey", "" }
                    //            } },
                    //            {"needOpinion", new Dictionary<string, object>() {
                    //                {"show", false },
                    //                {"col", 0 },
                    //                {"row", 0 }
                    //            }}
                    //        }
                    //},
                    {"NODE0009", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 },
                                    {"targetNodeKey", "" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 }
                                }}
                            }
                    }
                };
                return new JsonNetResult(new
                {
                    Succeed = true,
                    Data = new
                    {
                        mid = mid,
                        nid = nodeKey,
                        sid = worksheet.WorksheetID,
                        control = canChaneOpinion == true ? null : (string.IsNullOrEmpty(nodeKey) ? null : control[nodeKey]),
                        documentTitleName = documentTitleName,
                        attachments = fileInternalValueList,
                        detpAttachments = detpAttachments,
                        modify = new Dictionary<string, object>()
                        {
                            {"show", canChaneOpinion },
                            {"oldOpinion", resultDict.Count == 0 ? string.Empty : resultDict["opinion"] },
                            {"order", resultDict.Count == 0 ? string.Empty : resultDict["order"] }
                        }
                    }
                });
            }
            #endregion
            #region 下级办件收文
            else if(MessageTypeKey == WHConstants.Workflow_XiaJi_MessageID)
            {
                var MessageID = mid;
                WorkflowMgr mgr = new WorkflowMgr();
                OrgMgr orgMgr = new OrgMgr();
                Doc doc = mgr.GetDocByWorksheetID(mgr.GetDocHelperIdByMessageId(MessageID));
                Worksheet worksheet = doc.Worksheet;
                //公文标题
                var documentTitle = worksheet.GetWorkcell(6, 4);
                var documentTitleName = documentTitle != null ? documentTitle.WorkcellValue : null;
                //WKF_WorkflowHistory
                //var nodeSql = string.Format(@"select CONVERT( nvarchar(50), WH_ID),NodeKey from WKF_WorkflowHistory where MessageID = '{0}'  order by HandledTime DESC", mid);
                //var nodeInfo = DbUtil.ExcuteSqlCommand(nodeSql, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
                //var nodeInfoDic = ((Dictionary<string, string>)nodeInfo).FirstOrDefault();
                //var nodeKey = nodeInfoDic.Value;
                var nodeKey = "";
                List<Node> source = mgr.ListNodeToBeHandle(employee.EmplID, "");
                foreach (Node node in source)
                {
                    if (node.MessageID == mid)
                    {
                        // 判断是否是传阅节点
                        if (node.NodeKey.StartsWith(WHConstants.Transfer_Node_Key_Header))
                        {
                            // 将Messagehandle中该数据清除掉
                            mgr.DelMessageHandle(mid, node.NodeKey, employee.EmplID);
                            // 添加到WorkflowHistory
                            var workflowHistory = new WorkflowHistory();
                            workflowHistory.MessageID = mid;
                            workflowHistory.NodeName = "(转发传阅)";
                            workflowHistory.NodeKey = node.NodeKey;
                            workflowHistory.HandledBy = employee.EmplID;
                            workflowHistory.HandledTime = DateTime.Now;
                            workflowHistory.ProcType = 3;
                            mgr.AddWorkflowHistory(workflowHistory);
                            continue;
                        }
                        else
                        {
                            nodeKey = node.NodeKey;
                            break;
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                //附件信息
                var workcellFile = worksheet.GetWorkcell(7, 4);
                var fileValue = workcellFile != null ? workcellFile.WorkcellValue : null;
                var fileInternalValue = workcellFile != null ? workcellFile.WorkcellInternalValue : null;
                var fileInternalValues = fileInternalValue.Split(';');
                var fileInternalValueList = new List<object>();

                if (!string.IsNullOrWhiteSpace(fileInternalValues.FirstOrDefault()))
                {
                    for (int i = 0; i < fileInternalValues.Count(); i++)
                    {
                        var info = string.Format(@"Apps/Workflow/Running/ShowPreview/{0}?page=0", fileInternalValues[i]);
                        var fileSql = string.Format(@"select AttFileName,AttExtension from WKF_WorkflowAttachment where AttID = '{0}'", fileInternalValues[i]);
                        var fileResults = DbUtil.ExcuteSqlCommand(fileSql, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
                        Dictionary<string, string> dict = new Dictionary<string, string>();
                        Dictionary<string, string> fileInfo = (Dictionary<string, string>)fileResults;
                        var attFileName = string.Empty;
                        var attExtension = string.Empty;
                        if (!string.IsNullOrWhiteSpace(fileInfo.ToString()))
                        {
                            attFileName = fileInfo.FirstOrDefault().Key;
                            attExtension = fileInfo.FirstOrDefault().Value;
                        }


                        fileInternalValueList.Add(new
                        {
                            AttId = fileInternalValues[i],
                            AttFileName = attFileName
                        });
                    }
                }
                // TODO: 部门附件列表
                var detpAttachments = new List<object>();
                var deptCellFile = worksheet.GetWorkcell(14, 4);
                var deptFileValue = deptCellFile != null ? deptCellFile.WorkcellValue : null;
                if (deptFileValue != null)
                {
                    var deptFileInternalValue = deptCellFile != null ? deptCellFile.WorkcellInternalValue : null;
                    var deptFileInternalValues = deptFileInternalValue.Split(';');
                    if (!string.IsNullOrWhiteSpace(deptFileInternalValues.FirstOrDefault()))
                    {
                        for (int i = 0; i < deptFileInternalValues.Count(); i++)
                        {
                            var info = string.Format(@"Apps/Workflow/Running/ShowPreview/{0}", deptFileInternalValues[i]);
                            var fileSql = string.Format(@"select AttFileName,AttExtension from WKF_WorkflowAttachment where AttID = '{0}'", deptFileInternalValues[i]);
                            var fileResults = DbUtil.ExcuteSqlCommand(fileSql, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
                            Dictionary<string, string> dict = new Dictionary<string, string>();
                            Dictionary<string, string> fileInfo = (Dictionary<string, string>)fileResults;
                            var attFileName = string.Empty;
                            var attExtension = string.Empty;
                            if (!string.IsNullOrWhiteSpace(fileInfo.ToString()))
                            {
                                attFileName = fileInfo.FirstOrDefault().Key;
                                attExtension = fileInfo.FirstOrDefault().Value;
                            }
                            detpAttachments.Add(new
                            {
                                AttId = deptFileInternalValues[i],
                                AttFileName = attFileName,
                                DeptName = ""
                            });
                        }
                    }
                }
                // 是否可以编辑领导意见
                var canChaneOpinion = WorkflowUtil.CanChangeOpinion(mid, employee);
                Dictionary<string, string> resultDict = new Dictionary<string, string>();
                // 返回历史领导节点
                if (canChaneOpinion)
                {
                    nodeKey = WHConstants.Workflow_XiaJi_Leader_Node;
                    resultDict = WorkflowUtil.GetLatestOpinion(mid, nodeKey, employee);
                }
                // 流程控制信息
                var control = new Dictionary<string, object>()
                {
                    {"NODE0002", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 },
                                    {"targetNodeKey", "" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 }
                                }}
                            }
                    },
                    {"NODE0003", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 },
                                    {"targetNodeKey", "" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", true },
                                    {"col", 4 },
                                    {"row", 8 }
                                }},
                                {"saveCell", new List<object>() {
                                    new Dictionary<string, object>()
                                    {
                                        {"type", "name" }, { "row", 9 }, {"col", 5 }
                                    },
                                    new Dictionary<string, object>()
                                    {
                                        {"type", "date" }, { "row", 9 }, {"col", 8 }
                                    }
                                }}
                            }
                    },
                    {"NODE0004", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 },
                                    {"targetNodeKey", "" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 }
                                }}
                            }
                    },
                    {"NODE0005", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", true },
                                    {"col", 4 },
                                    {"row", 10 },
                                    {"targetNodeKey", "NODE0004" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", true },
                                    {"col", 4 },
                                    {"row", 10 }
                                }}
                            }
                    },
                    {"NODE0006", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", true },
                                    {"col", 4 },
                                    {"row", 12 },
                                    {"targetNodeKey", "NODE0004" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", true },
                                    {"col", 4 },
                                    {"row", 12 }
                                }}
                            }
                    },
                    {"NODE0007", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 },
                                    {"targetNodeKey", "0" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 }
                                }}
                            }
                    },
                    {"NODE0008", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 },
                                    {"targetNodeKey", "0" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 }
                                }}
                            }
                    },
                    //{"NODE0009", new Dictionary<string, object>(){
                    //            {"showReadedButton", new Dictionary<string, object>() {
                    //                {"show", false },
                    //                {"col", 0 },
                    //                {"row", 0 },
                    //                {"targetNodeKey", "0" }
                    //            } },
                    //            {"needOpinion", new Dictionary<string, object>() {
                    //                {"show", false },
                    //                {"col", 0 },
                    //                {"row", 0 }
                    //            }}
                    //        }
                    //},
                    {"NODE0010", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 },
                                    {"targetNodeKey", "0" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 }
                                }}
                            }
                    },
                    //{"NODE0011", new Dictionary<string, object>(){
                    //            {"showReadedButton", new Dictionary<string, object>() {
                    //                {"show", false },
                    //                {"col", 0 },
                    //                {"row", 0 },
                    //                {"targetNodeKey", "0" }
                    //            } },
                    //            {"needOpinion", new Dictionary<string, object>() {
                    //                {"show", false },
                    //                {"col", 0 },
                    //                {"row", 0 }
                    //            }}
                    //        }
                    //},
                };
                
                return new JsonNetResult(new
                {
                    Succeed = true,
                    Data = new {
                        mid = mid,
                        nid = nodeKey,
                        sid = worksheet.WorksheetID,
                        control = canChaneOpinion == true ? null : (string.IsNullOrEmpty(nodeKey) ? null : control[nodeKey]),
                        documentTitleName = documentTitleName,
                        attachments = fileInternalValueList,
                        detpAttachments = detpAttachments,
                        modify = new Dictionary<string, object>()
                        {
                            {"show", canChaneOpinion },
                            {"oldOpinion", resultDict.Count == 0 ? string.Empty : resultDict["opinion"] },
                            {"order", resultDict.Count == 0 ? string.Empty : resultDict["order"] }
                        }
                    }
                });
            }
            #endregion
            #region 上级办件收文流程
            else
            {
                var MessageID = mid;
                WorkflowMgr mgr = new WorkflowMgr();
                OrgMgr orgMgr = new OrgMgr();
                Doc doc = mgr.GetDocByWorksheetID(mgr.GetDocHelperIdByMessageId(MessageID));
                Worksheet worksheet = doc.Worksheet;

                //公文标题
                var documentTitle = worksheet.GetWorkcell(6, 4);
                var documentTitleName = documentTitle != null ? documentTitle.WorkcellValue : null;

                //WKF_WorkflowHistory
                //var nodeSql = string.Format(@"select CONVERT( nvarchar(50), WH_ID),NodeKey from WKF_WorkflowHistory where MessageID = '{0}'  order by HandledTime DESC", mid);
                //var nodeInfo = DbUtil.ExcuteSqlCommand(nodeSql, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
                //var nodeInfoDic = ((Dictionary<string, string>)nodeInfo).FirstOrDefault();
                //var nodeKey = nodeInfoDic.Value;
                var nodeKey = "";
                List<Node> source = mgr.ListNodeToBeHandle(employee.EmplID, "");
                foreach (Node node in source)
                {
                    if (node.MessageID == mid)
                    {
                        // 判断是否是传阅节点
                        if (node.NodeKey.StartsWith(WHConstants.Transfer_Node_Key_Header))
                        {
                            // 将Messagehandle中该数据清除掉
                            mgr.DelMessageHandle(mid, node.NodeKey, employee.EmplID);
                            // 添加到WorkflowHistory
                            var workflowHistory = new WorkflowHistory();
                            workflowHistory.MessageID = mid;
                            workflowHistory.NodeName = "(转发传阅)";
                            workflowHistory.NodeKey = node.NodeKey;
                            workflowHistory.HandledBy = employee.EmplID;
                            workflowHistory.HandledTime = DateTime.Now;
                            workflowHistory.ProcType = 3;
                            mgr.AddWorkflowHistory(workflowHistory);
                            continue;
                        }
                        else
                        {
                            nodeKey = node.NodeKey;
                            break;
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                //附件信息
                var workcellFile = worksheet.GetWorkcell(7, 4);
                var fileValue = workcellFile != null ? workcellFile.WorkcellValue : null;
                var fileInternalValue = workcellFile != null ? workcellFile.WorkcellInternalValue : null;
                var fileInternalValues = fileInternalValue.Split(';');
                var fileInternalValueList = new List<object>();
                if (!string.IsNullOrWhiteSpace(fileInternalValues.FirstOrDefault()))
                {
                    for (int i = 0; i < fileInternalValues.Count(); i++)
                    {
                        var info = string.Format(@"Apps/Workflow/Running/ShowPreview/{0}", fileInternalValues[i]);
                        var fileSql = string.Format(@"select AttFileName,AttExtension from WKF_WorkflowAttachment where AttID = '{0}'", fileInternalValues[i]);
                        var fileResults = DbUtil.ExcuteSqlCommand(fileSql, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
                        Dictionary<string, string> dict = new Dictionary<string, string>();
                        Dictionary<string, string> fileInfo = (Dictionary<string, string>)fileResults;
                        var attFileName = string.Empty;
                        var attExtension = string.Empty;
                        if (!string.IsNullOrWhiteSpace(fileInfo.ToString()))
                        {
                            attFileName = fileInfo.FirstOrDefault().Key;
                            attExtension = fileInfo.FirstOrDefault().Value;
                        }
                        fileInternalValueList.Add(new
                        {
                            AttId = fileInternalValues[i],
                            AttFileName = attFileName
                        });
                    }
                }
                // TODO: 部门附件列表
                var detpAttachments = new List<object>();
                var deptCellFile = worksheet.GetWorkcell(14, 4);
                var deptFileValue = deptCellFile != null ? deptCellFile.WorkcellValue : null;
                if (deptFileValue != null)
                {
                    var deptFileInternalValue = deptCellFile != null ? deptCellFile.WorkcellInternalValue : null;
                    var deptFileInternalValues = deptFileInternalValue.Split(';');
                    if (!string.IsNullOrWhiteSpace(deptFileInternalValues.FirstOrDefault()))
                    {
                        for (int i = 0; i < deptFileInternalValues.Count(); i++)
                        {
                            var info = string.Format(@"Apps/Workflow/Running/ShowPreview/{0}", deptFileInternalValues[i]);
                            var fileSql = string.Format(@"select AttFileName,AttExtension from WKF_WorkflowAttachment where AttID = '{0}'", deptFileInternalValues[i]);
                            var fileResults = DbUtil.ExcuteSqlCommand(fileSql, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
                            Dictionary<string, string> dict = new Dictionary<string, string>();
                            Dictionary<string, string> fileInfo = (Dictionary<string, string>)fileResults;
                            var attFileName = string.Empty;
                            var attExtension = string.Empty;
                            if (!string.IsNullOrWhiteSpace(fileInfo.ToString()))
                            {
                                attFileName = fileInfo.FirstOrDefault().Key;
                                attExtension = fileInfo.FirstOrDefault().Value;
                            }
                            detpAttachments.Add(new
                            {
                                AttId = deptFileInternalValues[i],
                                AttFileName = attFileName,
                                DeptName = ""
                            });
                        }
                    }
                }
                //审批信息
                var approveInfo = new
                {
                    FileInfo = new
                    {
                        FileValue = fileValue,
                        FileInternalValue = fileInternalValue,
                        FileInternalValueList = fileInternalValueList
                    }
                };
                // 是否可以编辑领导意见
                var canChaneOpinion = WorkflowUtil.CanChangeOpinion(mid, employee);
                Dictionary<string, string> resultDict = new Dictionary<string, string>();
                // 返回历史领导节点
                if (canChaneOpinion)
                {
                    nodeKey = WHConstants.Workflow_ShangJi_Leader_Node;
                    resultDict = WorkflowUtil.GetLatestOpinion(mid, nodeKey, employee);
                }
                // 流程控制信息
                var control = new Dictionary<string, object>()
                {
                    {"NODE0002", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 },
                                    {"targetNodeKey", "" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", true },
                                    {"col", 4 },
                                    {"row", 8 }
                                }},
                                {"saveCell", new List<object>() {
                                    new Dictionary<string, object>()
                                    {
                                        {"type", "name" }, { "row", 9 }, {"col", 5 }
                                    },
                                    new Dictionary<string, object>()
                                    {
                                        {"type", "date" }, { "row", 9 }, {"col", 8 }
                                    }
                                }}
                            }
                    },
                    {"NODE0003", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 },
                                    {"targetNodeKey", "" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 }
                                }}
                            }
                    },
                    {"NODE0004", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", true },
                                    {"col", 4 },
                                    {"row", 10 },
                                    {"targetNodeKey", "NODE0003" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", true },
                                    {"col", 4 },
                                    {"row", 10 }
                                }}
                            }
                    },
                    {"NODE0005", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", true },
                                    {"col", 4 },
                                    {"row", 12 },
                                    {"targetNodeKey", "NODE0003" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", true },
                                    {"col", 4 },
                                    {"row", 12 }
                                }}
                            }
                    },
                    //{"NODE0006", new Dictionary<string, object>(){
                    //            {"showReadedButton", new Dictionary<string, object>() {
                    //                {"show", false },
                    //                {"col", 0 },
                    //                {"row", 0 },
                    //                {"targetNodeKey", "" }
                    //            } },
                    //            {"needOpinion", new Dictionary<string, object>() {
                    //                {"show", false },
                    //                {"col", 0 },
                    //                {"row", 0 }
                    //            }}
                    //        }
                    //},
                    //{"NODE0007", new Dictionary<string, object>(){
                    //            {"showReadedButton", new Dictionary<string, object>() {
                    //                {"show", false },
                    //                {"col", 0 },
                    //                {"row", 0 },
                    //                {"targetNodeKey", "" }
                    //            } },
                    //            {"needOpinion", new Dictionary<string, object>() {
                    //                {"show", false },
                    //                {"col", 0 },
                    //                {"row", 0 }
                    //            }}
                    //        }
                    //},
                    {"NODE0008", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 },
                                    {"targetNodeKey", "" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 }
                                }}
                            }
                    },
                    {"NODE0009", new Dictionary<string, object>(){
                                {"showReadedButton", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 },
                                    {"targetNodeKey", "" }
                                } },
                                {"needOpinion", new Dictionary<string, object>() {
                                    {"show", false },
                                    {"col", 0 },
                                    {"row", 0 }
                                }}
                            }
                    }
                };
                return new JsonNetResult(new
                {
                    Succeed = true,
                    Data = new
                    {
                        mid = mid,
                        nid = nodeKey,
                        sid = worksheet.WorksheetID,
                        control = canChaneOpinion == true ? null : (string.IsNullOrEmpty(nodeKey) ? null : control[nodeKey]),
                        documentTitleName = documentTitleName,
                        attachments = fileInternalValueList,
                        detpAttachments = detpAttachments,
                        modify = new Dictionary<string, object>()
                        {
                            {"show", canChaneOpinion },
                            {"oldOpinion", resultDict.Count == 0 ? string.Empty : resultDict["opinion"] },
                            {"order", resultDict.Count == 0 ? string.Empty : resultDict["order"] }
                        }
                    }
                });
            }
            #endregion
        }
        #endregion

        #region 显示工作流详情页面
        public ActionResult GetDetailPage(string mid)
        {
            try
            {
                var sqlTemp = string.Format(@"select FromTemplate,MessageTypeKey from WKF_Message where MessageID = '{0}'", mid);
                var tempInfo = DbUtil.ExcuteSqlCommand(sqlTemp, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
                var tempInfoDic = ((Dictionary<string, string>)tempInfo).FirstOrDefault();
                var MessageTypeKey = tempInfoDic.Key;

                #region 阅件
                if (MessageTypeKey == WHConstants.Workflow_Read_MessageID)
                {
                    var MessageID = mid;
                    WorkflowMgr mgr = new WorkflowMgr();
                    OrgMgr orgMgr = new OrgMgr();
                    Doc doc = mgr.GetDocByWorksheetID(mgr.GetDocHelperIdByMessageId(MessageID));
                    Worksheet worksheet = doc.Worksheet;
                    //WKF_WorkflowHistory
                    var nodeSql = string.Format(@"select CONVERT( nvarchar(50), WH_ID),NodeKey from WKF_WorkflowHistory where MessageID = '{0}'  order by HandledTime DESC", mid);
                    var nodeInfo = DbUtil.ExcuteSqlCommand(nodeSql, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
                    var nodeInfoDic = ((Dictionary<string, string>)nodeInfo).FirstOrDefault();
                    var nodeKey = nodeInfoDic.Value;
                    var leaderNodeKey = WHConstants.Workflow_Read_Leader_Node;
                    //来文单位
                    var workcellUnit = worksheet.GetWorkcell(4, 2);
                    var workcellUnitValue = workcellUnit != null ? workcellUnit.WorkcellValue : null;
                    //来文单位名称
                    var workcellUnitName = worksheet.GetWorkcell(4, 4);
                    var workcellUnitNameValue = workcellUnitName != null ? workcellUnitName.WorkcellValue : null;
                    //来文文号
                    var workcellDocumentNumber = worksheet.GetWorkcell(5, 2);
                    var workcellDocumentValue = workcellDocumentNumber != null ? workcellDocumentNumber.WorkcellValue : null;
                    //来文文号内容
                    var workcellNumber = worksheet.GetWorkcell(5, 4);
                    var workcellNumberValue = workcellNumber != null ? workcellNumber.WorkcellValue : null;
                    //收文日期
                    var workcellClosedOrHairTime = worksheet.GetWorkcell(4, 6);
                    var workcellTimeName = workcellClosedOrHairTime != null ? workcellClosedOrHairTime.WorkcellValue : null;
                    //收文日期信息
                    var workcellTime = worksheet.GetWorkcell(4, 8);
                    var workcellTimeInfo = workcellTime != null ? workcellTime.WorkcellValue : null;
                    //公文标题
                    var documentTitle = worksheet.GetWorkcell(6, 2);
                    var documentTitleName = documentTitle != null ? documentTitle.WorkcellValue : null;
                    //标题内容
                    var title = worksheet.GetWorkcell(6, 4);
                    var titleInfo = title != null ? title.WorkcellValue : null;
                    //
                    var documentInfo = new DocumentInfo
                    {
                        WorkcellUnitValue = workcellUnitValue,
                        WorkcellUnitNameValue = workcellUnitNameValue,
                        WorkcellDocumentValue = workcellDocumentValue,
                        WorkcellNumberValue = workcellNumberValue,
                        WorkcellTimeName = workcellTimeName,
                        WorkcellTimeInfo = workcellTimeInfo,
                        DocumentTitleName = documentTitleName,
                        titleInfo = titleInfo,
                        MessageId = mid
                    };

                    //党政办签办
                    Workcell workcellDZBName = worksheet.GetWorkcell(8, 2);
                    var nameDZB = workcellDZBName != null ? workcellDZBName.WorkcellValue : null;
                    //党政办签办内容
                    Workcell workcellDZB = worksheet.GetWorkcell(8, 4);
                    var valueDZB = workcellDZB != null ? workcellDZB.WorkcellValue : null;
                    // 最新拟办意见
                    using(var db = new WhDbContext())
                    {
                        var nibanOpinion = db.NiBanOpinion.Where(n => n.MessageID == MessageID).FirstOrDefault();
                        if(nibanOpinion != null)
                        {
                            valueDZB = nibanOpinion.Opinion;
                        }
                    }
                    //签办人名称
                    Workcell workcellQB = worksheet.GetWorkcell(9, 5);
                    var valueQB = workcellQB != null ? workcellQB.WorkcellValue : null;
                    //签办人时间
                    Workcell workcellQBTime = worksheet.GetWorkcell(9, 8);
                    var timeQB = workcellQBTime != null ? workcellQBTime.WorkcellValue : null;
                    var approveDZB = new ApproveDZB
                    {
                        NameDZB = nameDZB,
                        ValueDZB = valueDZB,
                        ValueQB = valueQB,
                        TimeQB = timeQB
                    };
                    //领导审批意见
                    Workcell workcellLeader = worksheet.GetWorkcell(10, 2);
                    var valueLeader = workcellLeader != null ? workcellLeader.WorkcellValue : null;
                    //领导审批集合
                    List<LeaderHistoryInfo> historyInfo = new List<LeaderHistoryInfo>();

                    Workcell workcellLeaderApprove = worksheet.GetWorkcell(10, 4);
                    if (workcellLeaderApprove != null)
                    {
                        List<KeyValuePair<string, LeaderHistoryInfo>> itemList = new List<KeyValuePair<string, LeaderHistoryInfo>>();
                        List<string> list = new List<string>();

                        XmlNodeList history = workcellLeaderApprove.History;
                        // 新意见列表
                        var newOpinionList = whdb.NewOpinion.Where(n => n.MessageID == mid && n.NodeKey == leaderNodeKey).OrderBy(n => n.order).ToList();
                        // 每个用户对应签批数量
                        var nodeDict = new Dictionary<string, int>();
                        // 排序(默认从1开始)
                        var nodeOrderDict = new Dictionary<string, int>();

                        foreach (XmlNode node in history)
                        {
                            var emplId = node.Attributes.GetNamedItem("emplId").InnerText;
                            // 更新排序
                            if (nodeDict.ContainsKey(emplId))
                            {
                                int order = nodeDict[emplId];
                                nodeDict[emplId] = order + 1;
                            }
                            else
                            {
                                nodeDict.Add(emplId, 1);
                            }
                        }
                        foreach (XmlNode node in history)
                        {
                            var emplId = node.Attributes.GetNamedItem("emplId").InnerText;
                            var value = node.Attributes.GetNamedItem("Value").InnerText;
                            var updateTime = node.Attributes.GetNamedItem("UpdateTime").InnerText;

                            // 更新排序
                            if (nodeOrderDict.ContainsKey(emplId))
                            {
                                int order = nodeOrderDict[emplId];
                                nodeOrderDict[emplId] = order + 1;
                            }
                            else
                            {
                                nodeOrderDict.Add(emplId, 1);
                            }
                            var orderString = string.Empty;
                            // 查找是否有对应的新意见，使用新意见替换旧意见
                            foreach (TGR_NewOpinion newOpinion in newOpinionList)
                            {
                                // 同一个人的意见，且顺序相同就替换对应的签批意见
                                if (newOpinion.EmplID == emplId && nodeOrderDict[emplId] == newOpinion.order)
                                {
                                    value = newOpinion.Opinion;
                                    updateTime = newOpinion.UpdatedTime.Value.ToString("yyyy-%M-dd HH:mm");
                                    orderString = Convert.ToString(newOpinion.order);
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }

                            var historyEmpInfo = new LeaderHistoryInfo
                            {
                                EmplId = emplId,
                                EmplName = orgMgr.GetEmployee(emplId).EmplName,
                                Value = value,
                                UpdateTime = updateTime,
                                GlobalSortNo = string.Empty
                            };
                            //historyInfo.Add(historyEmpInfo);
                            itemList.Add(new KeyValuePair<string, LeaderHistoryInfo>(emplId, historyEmpInfo));
                            list.Add(emplId);
                        }

                        if (list.Count > 0)
                        {
                            var sql = @"SELECT EmplID, EmplName FROM ORG_Employee WHERE EmplID IN ({0}) ORDER BY GlobalSortNo DESC";
                            var results = DbUtil.ExcuteSqlCommand(string.Format(sql, string.Join(",", list)), DbUtil.WKF_GlobalSortNo);
                            Dictionary<string, string> orderredDict = (Dictionary<string, string>)results.ElementAt(0);
                            StringBuilder sb = new StringBuilder();

                            foreach (KeyValuePair<string, string> item in orderredDict)
                            {
                                foreach (KeyValuePair<string, LeaderHistoryInfo> innerItem in itemList)
                                {
                                    if (innerItem.Key == item.Key)
                                    {
                                        historyInfo.Add(innerItem.Value);
                                    }
                                }
                            }
                        }
                    }

                    //部门承办结果
                    Workcell workcellDept = worksheet.GetWorkcell(12, 2);
                    var nameDept = workcellDept != null ? workcellDept.WorkcellValue : null;
                    //部门承办记录
                    Workcell workcellDeptInfo = worksheet.GetWorkcell(12, 4);
                    List<HistoryDeptInfo> deptHistoryInfo = new List<HistoryDeptInfo>();
                    if (workcellDeptInfo != null)
                    {
                        XmlNodeList deptHistory = workcellDeptInfo.History;
                        foreach (XmlNode node in deptHistory)
                        {
                            var emplId = node.Attributes.GetNamedItem("emplId").InnerText;
                            var emplSql = string.Format(@"select EmplID,EmplName from ORG_Employee where EmplID = '{0}'", emplId);
                            var emplInfo = DbUtil.ExcuteSqlCommand(emplSql, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
                            var emplInfoDis = ((Dictionary<string, string>)emplInfo).FirstOrDefault();
                            var emplName = string.Empty;
                            if (!string.IsNullOrWhiteSpace(emplInfoDis.ToString()))
                            {
                                emplName = emplInfoDis.Value;
                            }
                            var value = node.Attributes.GetNamedItem("Value").InnerText;
                            var updateTime = node.Attributes.GetNamedItem("UpdateTime").InnerText;
                            var historyDeptInfo = new HistoryDeptInfo
                            {
                                EmplId = emplId,
                                EmplName = emplName,
                                Value = value,
                                UpdateTime = updateTime
                            };
                            deptHistoryInfo.Add(historyDeptInfo);
                        }
                    }

                    //审批信息
                    var approveInfo = new ApproveInfo
                    {
                        NodeKey = nodeKey,
                        DocumentInfo = documentInfo,
                        DZBInfo = approveDZB,
                        LeaderInfo = new LeaderInfo
                        {
                            ValueLeader = valueLeader,
                            LeaderHistoryInfo = historyInfo.OrderByDescending(m => !string.IsNullOrWhiteSpace(m.GlobalSortNo) ? Convert.ToInt32(m.GlobalSortNo) : 0).ToList()
                        },
                        DeptInfo = new DeptInfo
                        {
                            NameDept = nameDept,
                            DeptHistoryInfo = deptHistoryInfo
                        }
                    };
                    return View(approveInfo);
                }
                #endregion
                #region 下级办件收文
                else if (MessageTypeKey == WHConstants.Workflow_XiaJi_MessageID)
                {
                    var MessageID = mid;
                    WorkflowMgr mgr = new WorkflowMgr();
                    OrgMgr orgMgr = new OrgMgr();
                    Doc doc = mgr.GetDocByWorksheetID(mgr.GetDocHelperIdByMessageId(MessageID));
                    Worksheet worksheet = doc.Worksheet;
                    //WKF_WorkflowHistory
                    var nodeSql = string.Format(@"select CONVERT( nvarchar(50), WH_ID),NodeKey from WKF_WorkflowHistory where MessageID = '{0}'  order by HandledTime DESC", mid);
                    var nodeInfo = DbUtil.ExcuteSqlCommand(nodeSql, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
                    var nodeInfoDic = ((Dictionary<string, string>)nodeInfo).FirstOrDefault();
                    var nodeKey = nodeInfoDic.Value;
                    var leaderNodeKey = WHConstants.Workflow_XiaJi_Leader_Node;
                    //来文单位
                    var workcellUnit = worksheet.GetWorkcell(4, 2);
                    var workcellUnitValue = workcellUnit != null ? workcellUnit.WorkcellValue : null;
                    //来文单位名称
                    var workcellUnitName = worksheet.GetWorkcell(4, 4);
                    var workcellUnitNameValue = workcellUnitName != null ? workcellUnitName.WorkcellValue : null;
                    //来文文号
                    var workcellDocumentNumber = worksheet.GetWorkcell(5, 2);
                    var workcellDocumentValue = workcellDocumentNumber != null ? workcellDocumentNumber.WorkcellValue : null;
                    //来文文号内容
                    var workcellNumber = worksheet.GetWorkcell(5, 4);
                    var workcellNumberValue = workcellNumber != null ? workcellNumber.WorkcellValue : null;
                    //收文日期
                    var workcellClosedOrHairTime = worksheet.GetWorkcell(4, 6);
                    var workcellTimeName = workcellClosedOrHairTime != null ? workcellClosedOrHairTime.WorkcellValue : null;
                    //收文日期信息
                    var workcellTime = worksheet.GetWorkcell(4, 8);
                    var workcellTimeInfo = workcellTime != null ? workcellTime.WorkcellValue : null;
                    //公文标题
                    var documentTitle = worksheet.GetWorkcell(6, 2);
                    var documentTitleName = documentTitle != null ? documentTitle.WorkcellValue : null;
                    //标题内容
                    var title = worksheet.GetWorkcell(6, 4);
                    var titleInfo = title != null ? title.WorkcellValue : null;
                    //
                    var documentInfo = new DocumentInfo
                    {
                        WorkcellUnitValue = workcellUnitValue,
                        WorkcellUnitNameValue = workcellUnitNameValue,
                        WorkcellDocumentValue = workcellDocumentValue,
                        WorkcellNumberValue = workcellNumberValue,
                        WorkcellTimeName = workcellTimeName,
                        WorkcellTimeInfo = workcellTimeInfo,
                        DocumentTitleName = documentTitleName,
                        titleInfo = titleInfo,
                        MessageId = mid
                    };

                    //党政办签办
                    Workcell workcellDZBName = worksheet.GetWorkcell(8, 2);
                    var nameDZB = workcellDZBName != null ? workcellDZBName.WorkcellValue : null;
                    //党政办签办内容
                    Workcell workcellDZB = worksheet.GetWorkcell(8, 4);
                    var valueDZB = workcellDZB != null ? workcellDZB.WorkcellValue : null;
                    // 最新拟办意见
                    using (var db = new WhDbContext())
                    {
                        var nibanOpinion = db.NiBanOpinion.Where(n => n.MessageID == MessageID).FirstOrDefault();
                        if (nibanOpinion != null)
                        {
                            valueDZB = nibanOpinion.Opinion;
                        }
                    }
                    //签办人名称
                    Workcell workcellQB = worksheet.GetWorkcell(9, 5);
                    var valueQB = workcellQB != null ? workcellQB.WorkcellValue : null;
                    //签办人时间
                    Workcell workcellQBTime = worksheet.GetWorkcell(9, 8);
                    var timeQB = workcellQBTime != null ? workcellQBTime.WorkcellValue : null;
                    var approveDZB = new ApproveDZB
                    {
                        NameDZB = nameDZB,
                        ValueDZB = valueDZB,
                        ValueQB = valueQB,
                        TimeQB = timeQB
                    };
                    //领导审批意见
                    Workcell workcellLeader = worksheet.GetWorkcell(10, 2);
                    var valueLeader = workcellLeader != null ? workcellLeader.WorkcellValue : null;
                    //领导审批集合
                    List<LeaderHistoryInfo> historyInfo = new List<LeaderHistoryInfo>();

                    Workcell workcellLeaderApprove = worksheet.GetWorkcell(10, 4);
                    if (workcellLeaderApprove != null)
                    {
                        List<KeyValuePair<string, LeaderHistoryInfo>> itemList = new List<KeyValuePair<string, LeaderHistoryInfo>>();
                        List<string> list = new List<string>();

                        XmlNodeList history = workcellLeaderApprove.History;
                        // 新意见列表
                        var newOpinionList = whdb.NewOpinion.Where(n => n.MessageID == mid && n.NodeKey == leaderNodeKey).OrderBy(n => n.order).ToList();
                        // 每个用户对应签批数量
                        var nodeDict = new Dictionary<string, int>();
                        // 排序(默认从1开始)
                        var nodeOrderDict = new Dictionary<string, int>();

                        foreach (XmlNode node in history)
                        {
                            var emplId = node.Attributes.GetNamedItem("emplId").InnerText;
                            // 更新排序
                            if (nodeDict.ContainsKey(emplId))
                            {
                                int order = nodeDict[emplId];
                                nodeDict[emplId] = order + 1;
                            }
                            else
                            {
                                nodeDict.Add(emplId, 1);
                            }
                        }
                        foreach (XmlNode node in history)
                        {
                            var emplId = node.Attributes.GetNamedItem("emplId").InnerText;
                            var value = node.Attributes.GetNamedItem("Value").InnerText;
                            var updateTime = node.Attributes.GetNamedItem("UpdateTime").InnerText;

                            // 更新排序
                            if (nodeOrderDict.ContainsKey(emplId))
                            {
                                int order = nodeOrderDict[emplId];
                                nodeOrderDict[emplId] = order + 1;
                            }
                            else
                            {
                                nodeOrderDict.Add(emplId, 1);
                            }
                            var orderString = string.Empty;
                            // 查找是否有对应的新意见，使用新意见替换旧意见
                            foreach (TGR_NewOpinion newOpinion in newOpinionList)
                            {
                                // 同一个人的意见，且顺序相同就替换对应的签批意见
                                if (newOpinion.EmplID == emplId && nodeOrderDict[emplId] == newOpinion.order)
                                {
                                    value = newOpinion.Opinion;
                                    updateTime = newOpinion.UpdatedTime.Value.ToString("yyyy-%M-dd HH:mm");
                                    orderString = Convert.ToString(newOpinion.order);
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }

                            var historyEmpInfo = new LeaderHistoryInfo
                            {
                                EmplId = emplId,
                                EmplName = orgMgr.GetEmployee(emplId).EmplName,
                                Value = value,
                                UpdateTime = updateTime,
                                GlobalSortNo = string.Empty
                            };
                            //historyInfo.Add(historyEmpInfo);
                            itemList.Add(new KeyValuePair<string, LeaderHistoryInfo>(emplId, historyEmpInfo));
                            list.Add(emplId);
                        }

                        if (list.Count > 0)
                        {
                            var sql = @"SELECT EmplID, EmplName FROM ORG_Employee WHERE EmplID IN ({0}) ORDER BY GlobalSortNo";
                            var results = DbUtil.ExcuteSqlCommand(string.Format(sql, string.Join(",", list)), DbUtil.WKF_GlobalSortNo);
                            Dictionary<string, string> orderredDict = (Dictionary<string, string>)results.ElementAt(0);
                            StringBuilder sb = new StringBuilder();

                            foreach (KeyValuePair<string, string> item in orderredDict)
                            {
                                foreach (KeyValuePair<string, LeaderHistoryInfo> innerItem in itemList)
                                {
                                    if (innerItem.Key == item.Key)
                                    {
                                        historyInfo.Add(innerItem.Value);
                                    }
                                }
                            }
                        }
                    }

                    //部门承办结果
                    Workcell workcellDept = worksheet.GetWorkcell(12, 2);
                    var nameDept = workcellDept != null ? workcellDept.WorkcellValue : null;
                    //部门承办记录
                    List<HistoryDeptInfo> deptHistoryInfo = new List<HistoryDeptInfo>();
                    Workcell workcellDeptInfo = worksheet.GetWorkcell(12, 4);

                    if (workcellDeptInfo != null)
                    {
                        XmlNodeList deptHistory = workcellDeptInfo.History;

                        foreach (XmlNode node in deptHistory)
                        {
                            var emplId = node.Attributes.GetNamedItem("emplId").InnerText;
                            var emplSql = string.Format(@"select EmplID,EmplName from ORG_Employee where EmplID = '{0}'", emplId);
                            var emplInfo = DbUtil.ExcuteSqlCommand(emplSql, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
                            var emplInfoDis = ((Dictionary<string, string>)emplInfo).FirstOrDefault();
                            var emplName = string.Empty;
                            if (!string.IsNullOrWhiteSpace(emplInfoDis.ToString()))
                            {
                                emplName = emplInfoDis.Value;
                            }
                            var value = node.Attributes.GetNamedItem("Value").InnerText;
                            var updateTime = node.Attributes.GetNamedItem("UpdateTime").InnerText;
                            var historyDeptInfo = new HistoryDeptInfo
                            {
                                EmplId = emplId,
                                EmplName = emplName,
                                Value = value,
                                UpdateTime = updateTime
                            };
                            deptHistoryInfo.Add(historyDeptInfo);
                        }
                    }

                    //审批信息
                    var approveInfo = new ApproveInfo
                    {
                        NodeKey = nodeKey,
                        DocumentInfo = documentInfo,
                        DZBInfo = approveDZB,
                        LeaderInfo = new LeaderInfo
                        {
                            ValueLeader = valueLeader,
                            LeaderHistoryInfo = historyInfo
                        },
                        DeptInfo = new DeptInfo
                        {
                            NameDept = nameDept,
                            DeptHistoryInfo = deptHistoryInfo
                        }
                    };
                    return View(approveInfo);
                }
                #endregion
                #region 上级办件收文
                else
                {
                    var MessageID = mid;
                    WorkflowMgr mgr = new WorkflowMgr();
                    OrgMgr orgMgr = new OrgMgr();
                    Doc doc = mgr.GetDocByWorksheetID(mgr.GetDocHelperIdByMessageId(MessageID));
                    Worksheet worksheet = doc.Worksheet;
                    //WKF_WorkflowHistory
                    var nodeSql = string.Format(@"select CONVERT( nvarchar(50), WH_ID),NodeKey from WKF_WorkflowHistory where MessageID = '{0}'  order by HandledTime DESC", mid);
                    var nodeInfo = DbUtil.ExcuteSqlCommand(nodeSql, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
                    var nodeInfoDic = ((Dictionary<string, string>)nodeInfo).FirstOrDefault();
                    var nodeKey = nodeInfoDic.Value;
                    var leaderNodeKey = WHConstants.Workflow_ShangJi_Leader_Node;
                    //来文单位
                    var workcellUnit = worksheet.GetWorkcell(4, 2);
                    var workcellUnitValue = workcellUnit != null ? workcellUnit.WorkcellValue : null;
                    //来文单位名称
                    var workcellUnitName = worksheet.GetWorkcell(4, 4);
                    var workcellUnitNameValue = workcellUnitName != null ? workcellUnitName.WorkcellValue : null;
                    //来文文号
                    var workcellDocumentNumber = worksheet.GetWorkcell(5, 2);
                    var workcellDocumentValue = workcellDocumentNumber != null ? workcellDocumentNumber.WorkcellValue : null;
                    //来文文号内容
                    var workcellNumber = worksheet.GetWorkcell(5, 4);
                    var workcellNumberValue = workcellNumber != null ? workcellNumber.WorkcellValue : null;
                    //收文日期
                    var workcellClosedOrHairTime = worksheet.GetWorkcell(4, 6);
                    var workcellTimeName = workcellClosedOrHairTime != null ? workcellClosedOrHairTime.WorkcellValue : null;
                    //收文日期信息
                    var workcellTime = worksheet.GetWorkcell(4, 8);
                    var workcellTimeInfo = workcellTime != null ? workcellTime.WorkcellValue : null;
                    //公文标题
                    var documentTitle = worksheet.GetWorkcell(6, 2);
                    var documentTitleName = documentTitle != null ? documentTitle.WorkcellValue : null;
                    //标题内容
                    var title = worksheet.GetWorkcell(6, 4);
                    var titleInfo = title != null ? title.WorkcellValue : null;
                    //
                    var documentInfo = new DocumentInfo
                    {
                        WorkcellUnitValue = workcellUnitValue,
                        WorkcellUnitNameValue = workcellUnitNameValue,
                        WorkcellDocumentValue = workcellDocumentValue,
                        WorkcellNumberValue = workcellNumberValue,
                        WorkcellTimeName = workcellTimeName,
                        WorkcellTimeInfo = workcellTimeInfo,
                        DocumentTitleName = documentTitleName,
                        titleInfo = titleInfo,
                        MessageId = mid
                    };

                    //党政办签办
                    Workcell workcellDZBName = worksheet.GetWorkcell(8, 2);
                    var nameDZB = workcellDZBName != null ? workcellDZBName.WorkcellValue : null;
                    //党政办签办内容
                    Workcell workcellDZB = worksheet.GetWorkcell(8, 4);
                    var valueDZB = workcellDZB != null ? workcellDZB.WorkcellValue : null;
                    // 最新拟办意见
                    using (var db = new WhDbContext())
                    {
                        var nibanOpinion = db.NiBanOpinion.Where(n => n.MessageID == MessageID).FirstOrDefault();
                        if (nibanOpinion != null)
                        {
                            valueDZB = nibanOpinion.Opinion;
                        }
                    }
                    //签办人名称
                    Workcell workcellQB = worksheet.GetWorkcell(9, 5);
                    var valueQB = workcellQB != null ? workcellQB.WorkcellValue : null;
                    //签办人时间
                    Workcell workcellQBTime = worksheet.GetWorkcell(9, 8);
                    var timeQB = workcellQBTime != null ? workcellQBTime.WorkcellValue : null;
                    var approveDZB = new ApproveDZB
                    {
                        NameDZB = nameDZB,
                        ValueDZB = valueDZB,
                        ValueQB = valueQB,
                        TimeQB = timeQB
                    };
                    //领导审批意见
                    Workcell workcellLeader = worksheet.GetWorkcell(10, 2);
                    var valueLeader = workcellLeader != null ? workcellLeader.WorkcellValue : null;
                    //领导审批集合
                    List<LeaderHistoryInfo> historyInfo = new List<LeaderHistoryInfo>();

                    Workcell workcellLeaderApprove = worksheet.GetWorkcell(10, 4);
                    if (workcellLeaderApprove != null)
                    {
                        List<KeyValuePair<string, LeaderHistoryInfo>> itemList = new List<KeyValuePair<string, LeaderHistoryInfo>>();
                        List<string> list = new List<string>();

                        XmlNodeList history = workcellLeaderApprove.History;
                        // 新意见列表
                        var newOpinionList = whdb.NewOpinion.Where(n => n.MessageID == mid && n.NodeKey == leaderNodeKey).OrderBy(n => n.order).ToList();
                        // 每个用户对应签批数量
                        var nodeDict = new Dictionary<string, int>();
                        // 排序(默认从1开始)
                        var nodeOrderDict = new Dictionary<string, int>();

                        foreach (XmlNode node in history)
                        {
                            var emplId = node.Attributes.GetNamedItem("emplId").InnerText;
                            // 更新排序
                            if (nodeDict.ContainsKey(emplId))
                            {
                                int order = nodeDict[emplId];
                                nodeDict[emplId] = order + 1;
                            }
                            else
                            {
                                nodeDict.Add(emplId, 1);
                            }
                        }
                        foreach (XmlNode node in history)
                        {
                            var emplId = node.Attributes.GetNamedItem("emplId").InnerText;
                            var value = node.Attributes.GetNamedItem("Value").InnerText;
                            var updateTime = node.Attributes.GetNamedItem("UpdateTime").InnerText;

                            // 更新排序
                            if (nodeOrderDict.ContainsKey(emplId))
                            {
                                int order = nodeOrderDict[emplId];
                                nodeOrderDict[emplId] = order + 1;
                            }
                            else
                            {
                                nodeOrderDict.Add(emplId, 1);
                            }
                            var orderString = string.Empty;
                            // 查找是否有对应的新意见，使用新意见替换旧意见
                            foreach (TGR_NewOpinion newOpinion in newOpinionList)
                            {
                                // 同一个人的意见，且顺序相同就替换对应的签批意见
                                if (newOpinion.EmplID == emplId && nodeOrderDict[emplId] == newOpinion.order)
                                {
                                    value = newOpinion.Opinion;
                                    updateTime = newOpinion.UpdatedTime.Value.ToString("yyyy-%M-dd HH:mm");
                                    orderString = Convert.ToString(newOpinion.order);
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }

                            var historyEmpInfo = new LeaderHistoryInfo
                            {
                                EmplId = emplId,
                                EmplName = orgMgr.GetEmployee(emplId).EmplName,
                                Value = value,
                                UpdateTime = updateTime,
                                GlobalSortNo = string.Empty
                            };
                            //historyInfo.Add(historyEmpInfo);
                            itemList.Add(new KeyValuePair<string, LeaderHistoryInfo>(emplId, historyEmpInfo));
                            list.Add(emplId);
                        }

                        if (list.Count > 0)
                        {
                            var sql = @"SELECT EmplID, EmplName FROM ORG_Employee WHERE EmplID IN ({0}) ORDER BY GlobalSortNo DESC";
                            var results = DbUtil.ExcuteSqlCommand(string.Format(sql, string.Join(",", list)), DbUtil.WKF_GlobalSortNo);
                            Dictionary<string, string> orderredDict = (Dictionary<string, string>)results.ElementAt(0);
                            StringBuilder sb = new StringBuilder();

                            foreach (KeyValuePair<string, string> item in orderredDict)
                            {
                                foreach (KeyValuePair<string, LeaderHistoryInfo> innerItem in itemList)
                                {
                                    if (innerItem.Key == item.Key)
                                    {
                                        historyInfo.Add(innerItem.Value);
                                    }
                                }
                            }
                        }
                    }

                    //部门承办结果
                    Workcell workcellDept = worksheet.GetWorkcell(12, 2);
                    var nameDept = workcellDept != null ? workcellDept.WorkcellValue : null;
                    //部门承办记录
                    List<HistoryDeptInfo> deptHistoryInfo = new List<HistoryDeptInfo>();
                    Workcell workcellDeptInfo = worksheet.GetWorkcell(12, 4);

                    if (workcellDeptInfo != null)
                    {
                        XmlNodeList deptHistory = workcellDeptInfo.History;

                        foreach (XmlNode node in deptHistory)
                        {
                            var emplId = node.Attributes.GetNamedItem("emplId").InnerText;
                            var emplSql = string.Format(@"select EmplID,EmplName from ORG_Employee where EmplID = '{0}'", emplId);
                            var emplInfo = DbUtil.ExcuteSqlCommand(emplSql, DbUtil.WKF_GlobalSortNo).FirstOrDefault();
                            var emplInfoDis = ((Dictionary<string, string>)emplInfo).FirstOrDefault();
                            var emplName = string.Empty;
                            if (!string.IsNullOrWhiteSpace(emplInfoDis.ToString()))
                            {
                                emplName = emplInfoDis.Value;
                            }
                            var value = node.Attributes.GetNamedItem("Value").InnerText;
                            var updateTime = node.Attributes.GetNamedItem("UpdateTime").InnerText;
                            var historyDeptInfo = new HistoryDeptInfo
                            {
                                EmplId = emplId,
                                EmplName = emplName,
                                Value = value,
                                UpdateTime = updateTime
                            };
                            deptHistoryInfo.Add(historyDeptInfo);
                        }
                    }

                    //审批信息
                    var approveInfo = new ApproveInfo
                    {
                        NodeKey = nodeKey,
                        DocumentInfo = documentInfo,
                        DZBInfo = approveDZB,
                        LeaderInfo = new LeaderInfo
                        {
                            ValueLeader = valueLeader,
                            LeaderHistoryInfo = historyInfo
                        },
                        DeptInfo = new DeptInfo
                        {
                            NameDept = nameDept,
                            DeptHistoryInfo = deptHistoryInfo
                        }
                    };
                    return View(approveInfo);
                }
                #endregion
            }
            catch (Exception e)
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = e.Message
                });
            }
        }
        #endregion

        #region 展示部门指派页面
        public ActionResult ShowDepts()
        {
            return PartialView("ShowDepts");
        }
        #endregion

        #region 展示领导指派页面
        public ActionResult ShowLeaders()
        {
            return PartialView("ShowLeaders");
        }
        #endregion

        #region 根据GlobalSortNo获得排序后的发送列表
        /// <summary>
        /// 根据GlobalSortNo获得排序后的发送列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetOrderedSendList(FormCollection collection)
        {
            /*
             * 变量定义
             */
            // 字典存储对应变量
            Dictionary<string, string> OriginSendDict = new Dictionary<string, string>();
            // 排序顺序
            string Order = "ASC";
            // 流程管理
            WorkflowMgr wkfMgr = new WorkflowMgr();

            /*
             * 参数获取
             */
            // 消息ID
            var mid = collection["mid"];
            // 原始发送人列表字符串
            var OriginSendList = collection["emplIds"];

            /*
             * 参数校验
             */
            // 消息ID
            if(string.IsNullOrEmpty(mid))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "消息ID不能为空"
                });
            }
            // 原始发送人字符串
            if (string.IsNullOrEmpty(OriginSendList))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "发送人不能为空"
                });
            }

            /*
             * 判断顺序
             */
            var message = wkfMgr.GetMessage(mid);
            
            // 顺序
            if(message.FromTemplate != WHConstants.Workflow_XiaJi_MessageID)
            {
                Order = "DESC";
            }

            /*
             * 处理发送人
             */
            List<string> SendList = OriginSendList.Split(',').ToList();
            foreach(var sender in SendList)
            {
                List<string> sendArray = sender.Split('#').ToList();
                if(sendArray.Count == 1)
                {
                    OriginSendDict.Add(sendArray[0], sendArray[0]);
                } else
                {
                    OriginSendDict.Add(sendArray[0], sendArray[1]);
                }
            }

            /*
             * 根据处理人排序
             */
            List<string> keys = OriginSendDict.Keys.ToList();
            // 数据库查询
            var sql = @"SELECT EmplID FROM ORG_Employee WHERE EmplID IN ({0}) ORDER BY GlobalSortNo " + Order;
            List<object> results =  DbUtil.ExcuteSqlCommand(string.Format(sql, string.Join(",", keys)), DbUtil.WKF_OrderedSendList).ToList();

            // 构造排序后的处理人字符串
            StringBuilder sb = new StringBuilder();
            List<string> ResultList = new List<string>();

            foreach (string emplID in results)
            {
                var value = OriginSendDict[emplID];
                if(value == emplID)
                {
                    ResultList.Add(value);
                } else
                {
                    ResultList.Add(emplID + "#" + value);
                }
            }

            /*
             * 返回结果
             */
            return new JsonNetResult(new
            {
                Succeed = true,
                emplIds = string.Join(",", ResultList)
            });
        }
        #endregion

        #region 根据流程mid获得对应的Nodekey
        [HttpPost]
        public ActionResult GetHandledNodeKey(FormCollection collection)
        {
            try
            {
                /*
                 * 变量定义
                 */
                // 获得当前用户
                var employee = (User.Identity as AppkizIdentity).Employee;
                // 工作流Manager
                var workflowMgr = new WorkflowMgr();
                // 当前人处理节点列表
                var nodeKeyList = new List<string>();

                /*
                 * 参数获取
                 */
                // 流程ID
                var mid = collection["mid"];

                /*
                 * 参数校验
                 */
                // 流程ID
                if (string.IsNullOrEmpty(mid)) {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "流程ID不能为空"
                    });
                }

                /*
                 * 获取对应的流程处理记录
                 */
                Message message = workflowMgr.GetMessage(mid);
                if(message == null)
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "流程不存在"
                    });
                } else
                {
                    // 获得对应的工作流历史
                    List<WorkflowHistory> workflowHistoryList = message.History;
                    foreach(WorkflowHistory history in workflowHistoryList)
                    {
                        // 判断是否是当前用户的节点
                        if(history.HandledBy == employee.EmplID)
                        {
                            nodeKeyList.Add(history.NodeKey);

                        }
                    }
                    return new JsonNetResult(new {
                        Succeed = true,
                        Data = new {
                            nodekeys = nodeKeyList
                        }
                    });
                }
            }
            catch
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "用户未登录"
                });
            }
            


        }
        #endregion

        #region 检查是否有重新指派部门的权限
        [HttpPost]
        public ActionResult CheckAddHandlePermission(FormCollection collection)
        {
            /*
             * 变量定义
             */
            // 流程管理
            WorkflowMgr wkfMgr = new WorkflowMgr();
            // 当前用户
            var employee = (User.Identity as AppkizIdentity).Employee;

            /*
             * 参数获取
             */
            // 消息ID
            var mid = collection["mid"];

            /*
             * 参数校验
             */
            // 消息ID
            if (string.IsNullOrEmpty(mid))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "消息ID不能为空"
                });
            }

            /*
             * 获得该流程对应的节点
             */
            Dictionary<string, string> NodeDict = WorkflowUtil.GetWorkflowNode(mid);
            if (NodeDict == null)
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "流程不存在或该流程暂不支持"
                });
            }
            else
            {
                // 文电科转发节点
                var ForwardNodeKey = NodeDict["forward"];
                // 领导节点
                var LeaderNodeKey = NodeDict["leader"];
                // 部门节点
                var DeptNodeKey = NodeDict["dept"];
                var DeptNode = wkfMgr.GetNode(mid, DeptNodeKey);
                if (DeptNode == null)
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "节点不存在"
                    });
                }
                else
                {
                    // 检测当前流程是否在领导或部门节点
                    List<MessageHandle> leaderHandle = wkfMgr.FindMessageHandle(mid, LeaderNodeKey);
                    List<MessageHandle> deptHandle = wkfMgr.FindMessageHandle(mid, DeptNodeKey);

                    // 如果当前节点在领导或部门节点，则允许文电科指定部门
                    if (leaderHandle.Count == 0 && deptHandle.Count == 0)
                    {
                        return new JsonNetResult(new
                        {
                            Succeed = false,
                            Message = "当前不允许指派部门"
                        });
                    }
                }

                // 获得当前处理人的历史处理节点，判断文电科转发节点是否在历史记录中
                List<string> nodeKeyList = WorkflowUtil.GetWorkflowHistory(mid, employee.EmplID);
                if(nodeKeyList.Contains(ForwardNodeKey))
                {
                    return new JsonNetResult(new
                    {
                        Succeed = true,
                        Message = "具有指派部门权限"
                    });
                } else
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "没有指派部门权限"
                    });
                }
            }
            
        }
        #endregion

        #region 检查是否弹出提醒的权限
        [HttpPost]
        public ActionResult CheckNotifyPermission(FormCollection collection)
        {
            /*
             * 变量声明
             */
            // 消息管理
            WorkflowMgr wkfMgr = new WorkflowMgr();
            // 提醒权限
            bool hasNotifyPermission = false;

            /*
             * 参数获取
             */
            // 消息ID
            var mid = collection["mid"];
            // 节点ID
            var nid = collection["nid"];

            /*
             * 参数校验
             */
            // 消息ID
            if(string.IsNullOrEmpty(mid))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "消息ID不能为空"
                });
            }
            // 节点ID
            if(string.IsNullOrEmpty(nid))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "节点ID不能为空"
                });
            }
            /*
             * 获取当前消息
             */
            Message message = wkfMgr.GetMessage(mid);
            if(message == null)
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "消息不存在"
                });
            }
            else
            {
                // 获取模板ID
                var templateID = message.FromTemplate;
                if(templateID == WHConstants.Workflow_Read_MessageID &&
                    nid == WHConstants.Workflow_Read_Forward_Node)
                {
                    hasNotifyPermission = true;
                } else if(templateID == WHConstants.Workflow_XiaJi_MessageID &&
                    nid == WHConstants.Workflow_XiaJi_Forward_Node)
                {
                    hasNotifyPermission = true;
                } else if(templateID == WHConstants.Workflow_ShangJi_MessageID &&
                    nid == WHConstants.Workflow_ShangJi_Forward_Node)
                {
                    hasNotifyPermission = true;
                } else
                {
                    hasNotifyPermission = false;
                }

                return new JsonNetResult(new
                {
                    Succeed = hasNotifyPermission,
                });
            }
        }
        #endregion

        #region 添加修改提醒
        /// <summary>
        /// 
        /// </summary>
        /// <param name="collection">
        /// targets:[{"nid":"NODE0004","empl":"1,2,3#4", ordered:"true"}]
        /// </param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddNotifyRecord(FormCollection collection)
        {
            try
            {
                /*
                 * 变量定义
                 */
                WorkflowMgr wkfMgr = new WorkflowMgr();

                var employee = (User.Identity as AppkizIdentity).Employee;

                /*
                 * 参数获取
                 */
                // Json化后的字符串
                // 消息ID
                var mid = collection["mid"];
                // 当前节点ID
                var nodekey = collection["nodekey"];
                // 提醒人列表 :[{nid,empl}]
                var jsonTargets = collection["nlist"];

                /*
                 * 参数校验
                 */
                // 消息ID
                if (string.IsNullOrEmpty(mid))
                {
                    LogService.WriteLog("Tiger", "Message:" + string.Format("Employee:{0}, Msg:{1}",employee.EmplID, "消息ID不能为空"), "AddNotifyRecord_Debug", LogService.LogLevel.Debug);

                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "消息ID不能为空"
                    });
                }
                // 节点ID
                if (string.IsNullOrEmpty(nodekey))
                {
                    LogService.WriteLog("Tiger", "Message:" + string.Format("Employee:{0}, Msg:{1}", employee.EmplID, "节点ID不能为空"), "AddNotifyRecord_Debug", LogService.LogLevel.Debug);

                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "节点ID不能为空"
                    });
                }
                // 发送人数据
                if (string.IsNullOrEmpty(jsonTargets))
                {
                    LogService.WriteLog("Tiger", "Message:" + string.Format("Employee:{0}, Msg:{1}", employee.EmplID, "提醒数据为空"), "AddNotifyRecord_Debug", LogService.LogLevel.Debug);

                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "提醒数据为空"
                    });
                }

                /*
                 * 发送提交提醒
                 */
                //SendSubmitNotify(collection);
                /*
                 * 判断是否应该设置提醒（文电科转发节点可以设置）
                 */
                bool canSendNotification = WorkflowUtil.CanSendNotification(mid, nodekey);
                if (canSendNotification)
                {
                    /*
                     * 数据处理
                     */
                    // 将Json字符串转化为字典数组
                    var records = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(jsonTargets);
                    foreach (Dictionary<string, string> dict in records)
                    {
                        // 节点ID
                        var nid = dict["nid"];
                        // 发送者
                        var senders = dict["empl"];
                        if (!string.IsNullOrEmpty(senders))
                        {
                            TGR_NotifyRecord notifyRecord = new TGR_NotifyRecord();
                            notifyRecord.MessageID = mid;
                            notifyRecord.NodeKey = nid;
                            notifyRecord.Senders = senders;
                            notifyRecord.Receivers = senders;
                            notifyRecord.CreateTime = DateTime.Now;
                            notifyRecord.UpdateTime = DateTime.Now;

                            whdb.NotifyRecord.Add(notifyRecord);
                            whdb.SaveChanges();
                        }
                    }
                    LogService.WriteLog("Tiger", "Message:" + string.Format("Employee:{0},MessageId:{1},NodeKey:{2},Msg:{3}", employee.EmplID, mid, nodekey, "提醒设置成功"), "AddNotifyRecord_Debug", LogService.LogLevel.Debug);

                    return new JsonNetResult(new
                    {
                        Succeed = true,
                        Message = "提醒设置成功"
                    });
                }

                // 判断是否是领导节点，如果是领导节点且提交的内容不为【已阅】时，发送通知给文电科
                // 或者当前节点为部门节点，且当前用户属于【部门领导组】成员
                Dictionary<string, string> nodeDict = WorkflowUtil.GetWorkflowNode(mid);
                if (nodeDict == null)
                {
                    LogService.WriteLog("Tiger", "Message:" + string.Format("Employee:{0},MessageId:{1},NodeKey:{2},Msg:{3}", employee.EmplID, mid, nodekey, "节点信息不存在"), "AddNotifyRecord_Debug", LogService.LogLevel.Debug);

                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "节点信息不存在"
                    });
                }
                else if (nodeDict["leader"] == nodekey)
                {
                    // 当前节点为领导节点，检测领导提交的最新内容
                    var resultDict = WorkflowUtil.GetLatestOpinion(mid, nodekey, employee);
                    if(resultDict.Count == 0)
                    {
                        LogService.WriteLog("Tiger", "Message:" + string.Format("Employee:{0},MessageId:{1},NodeKey:{2},Msg:{3}", employee.EmplID, mid, nodekey, "该节点没有查询到意见，是否不是领导节点"), "AddNotifyRecord_Debug", LogService.LogLevel.Debug);

                        return new JsonNetResult(new
                        {
                            Succeed = false,
                            Message = "该节点没有查询到意见，是否不是领导节点"
                        });
                    }
                    else
                    {
                        var opinion = resultDict["opinion"];
                        if(opinion.Trim() != WHConstants.Workflow_Opinion_Read)
                        {
                            return SendLeaderNotify(mid, nodekey, employee);
                        }
                        else
                        {
                            LogService.WriteLog("Tiger", "Message:" + string.Format("Employee:{0},MessageId:{1},NodeKey:{2},Msg:{3}", employee.EmplID, mid, nodekey, "领导意见为已阅，无须提醒"), "AddNotifyRecord_Debug", LogService.LogLevel.Debug);

                            return new JsonNetResult(new
                            {
                                Succeed = false,
                                Message = "领导意见为已阅，无须提醒"
                            });
                        }
                    }
                }
                else if(nodeDict["dept"] == nodekey)
                {
                    // 当前节点为部门节点，检测部门提交的最新内容
                    var resultDict = WorkflowUtil.GetDeptLatestOpinion(mid, nodekey, employee);
                    if (resultDict.Count == 0)
                    {
                        LogService.WriteLog("Tiger", "Message:" + string.Format("Employee:{0},MessageId:{1},NodeKey:{2},Msg:{3}", employee.EmplID, mid, nodekey, "该节点没有查询到意见，是否不是部门节点"), "AddNotifyRecord_Debug", LogService.LogLevel.Debug);

                        return new JsonNetResult(new
                        {
                            Succeed = false,
                            Message = "该节点没有查询到意见，是否不是部门节点"
                        });
                    }
                    else
                    {
                        var opinion = resultDict["opinion"];
                        if (opinion.Trim() != WHConstants.Workflow_Opinion_Read)
                        {
                            return SendLeaderNotify(mid, nodekey, employee);
                        }
                        else
                        {
                            LogService.WriteLog("Tiger", "Message:" + string.Format("Employee:{0},MessageId:{1},NodeKey:{2},Msg:{3}", employee.EmplID, mid, nodekey, "部门意见为已阅，无须提醒"), "AddNotifyRecord_Debug", LogService.LogLevel.Debug);

                            return new JsonNetResult(new
                            {
                                Succeed = false,
                                Message = "部门意见为已阅，无须提醒"
                            });
                        }
                    }
                }
                else
                {
                    LogService.WriteLog("Tiger", "Message:" + string.Format("Employee:{0},MessageId:{1},NodeKey:{2},Msg:{3}", employee.EmplID, mid, nodekey, "当前提交节点非领导或部门节点，无须提醒"), "AddNotifyRecord_Debug", LogService.LogLevel.Debug);

                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "当前提交节点非领导或部门节点，无须提醒"
                    });
                }
            }
            catch(Exception e)
            {
                LogService.WriteLog("Tiger", "Message:" + e.Message, "AddNotifyRecord_Debug", LogService.LogLevel.Debug);

                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = e.Message
                });
            }
        }
        #endregion

        #region 发送修改提醒
        [HttpPost]
        public ActionResult SendChangeNotify(FormCollection collection)
        {
            try
            {
                /*
                * 变量定义
                */
                // 流程管理
                WorkflowMgr wkfMgr = new WorkflowMgr();
                // 当前用户
                var employee = (User.Identity as AppkizIdentity).Employee;

                /*
                 * 参数获取
                 */
                // 流程ID
                var mid = collection["mid"];
                // 节点ID
                var nid = collection["nid"];

                /*
                 * 参数校验
                 */
                // 流程ID
                if (string.IsNullOrEmpty(mid))
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "流程ID不能为空"
                    });
                }
                // 节点ID
                if (string.IsNullOrEmpty(nid))
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "节点ID不能为空"
                    });
                }
                /*
                 * 处理发送逻辑
                 */
                // 文电领导通知人员:该人员可能在拟办，或者在部门承办节点
                var WendianNotifyList = WorkflowUtil.GetWendianLeaderList(mid, string.Empty, employee.EmplID);

                // 获得当前用户所在流程节点对应的接收人信息
                var sql = @"SELECT
                                Receivers
                            FROM 
                                TGR_NotifyRecord 
                            WHERE
                                MessageID = (
                                    select 
                                        MessageID 
                                    from 
                                        TGR_NotifyRecord 
                                    where 
                                        NodeKey='{0}' 
                                    and 
                                        CharIndex('{1}', Senders) > 0
                                    and
                                        MessageID = '{2}'
                                    group by MessageID)";
                List<object> receivers = DbUtil.ExcuteSqlCommand(string.Format(sql, nid, employee.EmplID, mid), DbUtil.WKF_NotifyReceivers).ToList();
                // 获得提醒人下级用户，进行提醒
                var notifySql = @"SELECT
	                                EmplID
                                FROM
	                                ORG_Employee 
                                WHERE 
	                                EmplID 
                                IN 
	                                ({0})
                                AND 
	                                GlobalSortNO < (SELECT GlobalSortNO FROM ORG_Employee WHERE EmplID='{1}')
                                AND 
	                                EmplID
                                IN 
	                                (SELECT HandledBy FROM WKF_WorkflowHistory WHERE MessageID='{2}')";
                List<object> targets = DbUtil.ExcuteSqlCommand(string.Format(notifySql, string.Join(",", receivers), employee.EmplID, mid), DbUtil.WKF_NotifyTargets).ToList();

                // 获得该流程已处理的人列表
                foreach (var target in targets)
                {
                    // 过滤【文电领导】列表内的人员
                    if(WendianNotifyList.Contains(target.ToString()))
                    {
                        targets.Remove(target);
                    }
                    else
                    {
                        bool SendSuccess = WorkflowUtil.SendNotification(mid, nid, target.ToString());
                        // 添加发送成功记录
                        if (SendSuccess)
                        {
                            TGR_SendNotifyRecord SendNotifyRecord = new TGR_SendNotifyRecord();
                            SendNotifyRecord.EmplID = target.ToString();
                            SendNotifyRecord.MessageID = mid;
                            SendNotifyRecord.AlreadyRead = false;
                            SendNotifyRecord.CreateTime = DateTime.Now;
                            SendNotifyRecord.UpdatedTime = DateTime.Now;

                            whdb.SendNotifyRecord.Add(SendNotifyRecord);
                        }
                        whdb.SaveChanges();
                    }
                }
                // 发送极光提醒
                // 根据消息ID获得对应的标题
                Message message = wkfMgr.GetMessage(mid);
                Dictionary<string, object> dict = new Dictionary<string, object>();

                dict["type"] = WHConstants.JPush_Workflow_Type;
                dict["title"] = string.Format("您有新的流程修改通知 \"{0}\"", message.MessageTitle);
                dict["content"] = new Dictionary<string, object>()
                {
                    {"mid",  mid}
                };
                WorkflowUtil.SendJPushNotification(targets, dict);

                return new JsonNetResult(new
                {
                    Succeed = true,
                    Message = "提醒发送成功"
                });
            }
            catch
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "提醒出错"
                });
            }
            
        }
        #endregion

        #region 发送提交提醒
        public ActionResult SendSubmitNotify(FormCollection collection)
        {
            /*
             * 变量定义
             */
            // 流程管理
            WorkflowMgr wkfMgr = new WorkflowMgr();
            // 依次处理标志
            bool orderedFlag = false;
            /*
             * 参数获取
             */
            // 消息ID
            var mid = collection["mid"];
            // 提醒人列表 :[{nid,empl}]
            var jsonTargets = collection["nlist"];

            /*
             * 参数校验
             */
            // 消息ID
            if (string.IsNullOrEmpty(mid))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "消息ID不能为空"
                });
            }

            /*
             * 发送处理
             */
            if (!string.IsNullOrEmpty(jsonTargets))
            {
                // 将Json字符串转化为字典数组
                var records = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(jsonTargets);
                foreach (Dictionary<string, string> record in records)
                {
                    // 节点ID
                    var nid = record["nid"];
                    // 发送者
                    var senders = record["empl"];
                    // 依次处理标志
                    var orderedString = record["ordered"];
                    // 依次处理
                    if (!string.IsNullOrEmpty(orderedString))
                    {
                        if (!bool.TryParse(orderedString, out orderedFlag))
                        {
                            return new JsonNetResult(new
                            {
                                Succeed = false,
                                Message = "依次处理标志应该为布尔型"
                            });
                        }
                    }
                    // 将发送者分成数组
                    var sendArray = senders.Split(',').ToList();
                    // 发送人列表
                    var targets = new List<object>();
                    foreach (var target in sendArray)
                    {
                        // 发送人
                        var targetUser = target;

                        // 检测代理人，推送只发给代理人
                        var targetArray = target.Split('#').ToList();
                        if (targetArray.Count == 2)
                        {
                            targetUser = targetArray[0];
                        }
                        targets.Add(targetUser);

                        // 依次处理，则只发送第一个人
                        if (orderedFlag == true)
                        {
                            break;
                        }
                    }
                    // 发送极光提醒
                    // 根据消息ID获得对应的标题
                    Message message = wkfMgr.GetMessage(mid);
                    Dictionary<string, object> dict = new Dictionary<string, object>();

                    dict["type"] = WHConstants.JPush_Workflow_Type;
                    dict["title"] = string.Format("您有新的流程提醒通知 \"{0}\"", message.MessageTitle);
                    dict["content"] = new Dictionary<string, object>()
                        {
                            {"mid",  mid}
                        };
                    WorkflowUtil.SendJPushNotification(targets, dict);
                }

                return new JsonNetResult(new
                {
                    Succeed = true,
                    Message = "发送提醒成功"
                });
            }
            else
            {
                // 结束节点没有提醒人，所以该种情况下也是正常响应
                return new JsonNetResult(new
                {
                    Succeed = true,
                    Message = "未指定提醒人"
                });
            }
        }
        #endregion

        #region 添加意见修改记录
        /// <summary>
        /// url: /Apps/Tiger/Workflow/AddNewOpinion
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddNewOpinion(FormCollection collection)
        {
            try
            {
                /*
                 * 变量定义
                 */
                // 当前用户
                var employee = (User.Identity as AppkizIdentity).Employee;
                // 流程管理
                WorkflowMgr mgr = new WorkflowMgr();
                // 当前用户评论总数
                int userTotalClount = 0;
                // 顺序
                int order = 0;

                /*
                 * 参数获取
                 */
                // 流程ID
                var mid = collection["mid"];
                // 节点ID
                var nid = collection["nid"];
                // 意见
                var opinion = collection["opinion"];
                // 顺序
                var orderString = collection["order"];

                /*
                 * 参数校验
                 */
                // 流程ID
                if (string.IsNullOrEmpty(mid))
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "消息ID不能为空"
                    });
                }
                // 节点ID
                if (string.IsNullOrEmpty(nid))
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "节点ID不能为空"
                    });
                }
                // 意见
                if (string.IsNullOrEmpty(opinion))
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "意见不能为空"
                    });
                }
                // 排序
                if(!string.IsNullOrEmpty(orderString))
                {
                    if(!int.TryParse(orderString, out order))
                    {
                        return new JsonNetResult(new
                        {
                            Succeed = false,
                            Message = "排序应为数字"
                        });
                    }
                }
                /*
                 * 插入意见
                 */
                Doc doc = mgr.GetDocByWorksheetID(mgr.GetDocHelperIdByMessageId(mid));
                Worksheet worksheet = doc.Worksheet;
                Workcell workcell = worksheet.GetWorkcell(10, 4);
                XmlNodeList history = workcell.History;
                foreach (XmlNode node in history)
                {
                    var emplId = node.Attributes.GetNamedItem("emplId").InnerText;
                    // 统计总数
                    if(employee.EmplID == emplId)
                    {
                        userTotalClount = userTotalClount + 1;
                    }
                }
                // 排序字段为空，则插入新的记录，新纪录的排序字段和总数保持一致（最新）
                // 由于是修改，且无法删除，所以userTotalCount总是会大于0
                if(string.IsNullOrEmpty(orderString))
                {
                    TGR_NewOpinion insertOpinion = new TGR_NewOpinion();
                    insertOpinion.EmplID = employee.EmplID;
                    insertOpinion.MessageID = mid;
                    insertOpinion.NodeKey = nid;
                    insertOpinion.Opinion = opinion;
                    insertOpinion.order = userTotalClount;
                    insertOpinion.CreateTime = DateTime.Now;
                    insertOpinion.UpdatedTime = DateTime.Now;
                    whdb.NewOpinion.Add(insertOpinion);
                }
                else
                {
                    // 更新已有记录
                    TGR_NewOpinion newOpinion = whdb.NewOpinion.Where(n => n.MessageID == mid && n.EmplID == employee.EmplID && n.order == order).FirstOrDefault();
                    if (newOpinion == null)
                    {
                        return new JsonNetResult(new
                        {
                            Succeed = false,
                            Message = "更新的记录不存在"
                        });
                    }
                    else
                    {
                        newOpinion.Opinion = opinion;
                        newOpinion.UpdatedTime = DateTime.Now;
                    }
                }

                whdb.SaveChanges();

                /*
                 * 修改后发送通知
                 */
                SendChangeNotify(collection);
                // 意见不为【已阅】时，发送给文电科通知
                if(opinion.Trim() != WHConstants.Workflow_Opinion_Read)
                {
                    SendLeaderNotify(mid, nid, employee);
                }

                return new JsonNetResult(new
                {
                    Succeed = true,
                    Message = "修改成功"
                });
            }
            catch
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "添加意见失败"
                });
            }
        }
        #endregion

        #region 添加部门指派
        [HttpPost]
        public ActionResult AddDeptMessageHandle(FormCollection collection)
        {
            /*
             * 变量定义
             */
            // 工作流管理
            WorkflowMgr wkfMgr = new WorkflowMgr();

            /*
             * 参数获取
             */
            // 消息ID
            var mid = collection["mid"];
            // 指定人员
            var empl = collection["empl"];

            /*
             * 参数校验
             */
            // 消息ID
            if(string.IsNullOrEmpty(mid))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "消息ID不能为空"
                });
            }
            // 指定人员
            if(string.IsNullOrEmpty(empl))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "指定人员不能为空"
                });
            }

            /*
             * 获得该流程对应的节点
             */
            Dictionary<string, string> NodeDict = WorkflowUtil.GetWorkflowNode(mid);
            if(NodeDict == null)
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "流程不存在或该流程暂不支持"
                });
            }
            else
            {
                // 文电科转发节点
                var ForwardNodeKey = NodeDict["forward"];
                // 领导节点
                var LeaderNodeKey = NodeDict["leader"];
                // 部门节点
                var DeptNodeKey = NodeDict["dept"];
                var DeptNode = wkfMgr.GetNode(mid, DeptNodeKey);
                if(DeptNode == null)
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "节点不存在"
                    });
                } else
                {
                    // 检测当前流程是否在领导或部门节点
                    List<MessageHandle> leaderHandle = wkfMgr.FindMessageHandle(mid, LeaderNodeKey);
                    List<MessageHandle> deptHandle = wkfMgr.FindMessageHandle(mid, DeptNodeKey);

                    // 如果当前节点在领导或部门节点，则允许文电科指定部门
                    if (leaderHandle.Count > 0 || deptHandle.Count > 0)
                    {
                        List<string> emplList = empl.Split(',').ToList();
                        foreach (var emplID in emplList)
                        {
                            // 用户ID
                            var UserID = string.Empty;
                            // 代理人ID
                            var EntrustBy = string.Empty;

                            // 判断emplID是否存在代理(a代理b，则为：a#b)
                            List<string> emplArray = emplID.Split('#').ToList();
                            if (emplArray.Count > 1)
                            {
                                UserID = emplArray[1];
                                EntrustBy = emplArray[0];
                            }
                            else
                            {
                                UserID = emplArray[0];
                            }
                            // 创建数据
                            MessageHandle Handle = new Appkiz.Apps.Workflow.Library.MessageHandle();
                            Handle.ActivatedByNodes = ForwardNodeKey;
                            Handle.ActivatedReason = 0;
                            Handle.CreateTime = DateTime.Now;
                            Handle.EntrustBy = EntrustBy;
                            Handle.HandleStatus = 0;
                            Handle.HandleType = 0;
                            Handle.Memo = string.Empty;
                            Handle.MessageID = mid;
                            Handle.NodeKey = DeptNodeKey;
                            Handle.NodeName = DeptNode.NodeName;
                            Handle.ProcType = 0;
                            Handle.SendBackThenReturnTo = string.Empty;
                            Handle.UserID = UserID;

                            wkfMgr.AddMessageHandle(Handle);
                            // 更新处理状态
                            Handle.HandleStatus = 1;
                            wkfMgr.UpdateMessageHandle(Handle);
                        }

                        return new JsonNetResult(new
                        {
                            Succeed = true,
                            Message = "添加部门指派成功"
                        });
                    }
                    else
                    {
                        return new JsonNetResult(new
                        {
                            Succeed = false,
                            Message = "当前不允许指定部门"
                        });
                    }
                }
            }
        }
        #endregion

        #region 添加领导指派
        [HttpPost]
        public ActionResult AddLeaderMessageHandle(FormCollection collection)
        {
            /*
             * 变量定义
             */
            // 工作流管理
            WorkflowMgr wkfMgr = new WorkflowMgr();

            /*
             * 参数获取
             */
            // 消息ID
            var mid = collection["mid"];
            // 指定人员
            var empl = collection["empl"];

            /*
             * 参数校验
             */
            // 消息ID
            if (string.IsNullOrEmpty(mid))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "消息ID不能为空"
                });
            }
            // 指定人员
            if (string.IsNullOrEmpty(empl))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "指定人员不能为空"
                });
            }

            /*
             * 获得该流程对应的节点
             */
            Dictionary<string, string> NodeDict = WorkflowUtil.GetWorkflowNode(mid);
            if (NodeDict == null)
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "流程不存在或该流程暂不支持"
                });
            }
            else
            {
                // 文电科转发节点
                var ForwardNodeKey = NodeDict["forward"];
                // 领导节点
                var LeaderNodeKey = NodeDict["leader"];
                // 部门节点
                var DeptNodeKey = NodeDict["dept"];
                var LeaderNode = wkfMgr.GetNode(mid, LeaderNodeKey);
                if (LeaderNode == null)
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "节点不存在"
                    });
                }
                else
                {
                    // 检测当前流程是否在领导或部门节点
                    List<MessageHandle> leaderHandle = wkfMgr.FindMessageHandle(mid, LeaderNodeKey);
                    List<MessageHandle> deptHandle = wkfMgr.FindMessageHandle(mid, DeptNodeKey);

                    // 如果当前节点在领导或部门节点，则允许文电科指定部门
                    if (leaderHandle.Count > 0 || deptHandle.Count > 0)
                    {
                        // 将新指派的用户添加到修改提醒列表中
                        TGR_NotifyRecord notifyRecord = whdb.NotifyRecord.Where(n => n.MessageID == mid && n.NodeKey == LeaderNodeKey).FirstOrDefault();
                        // 文电科还未指派领导和部门处理
                        if (notifyRecord == null)
                        {
                            return new JsonNetResult(new
                            {
                                Succeed = false,
                                Message = "文电科还未指派领导和部门处理"
                            });
                        }
                        else
                        {
                            // 正在处理领导列表，防止重复添加
                            List<string> LeadersHandle = leaderHandle.Select(n => n.UserID).ToList();
                            List<string> SenderList = notifyRecord.Senders.Split(',').ToList();
                            List<string> emplList = empl.Split(',').ToList();
                            foreach (var emplID in emplList)
                            {
                                // 用户ID
                                var UserID = string.Empty;
                                // 代理人ID
                                var EntrustBy = string.Empty;

                                // 判断emplID是否存在代理(a代理b，则为：a#b)
                                List<string> emplArray = emplID.Split('#').ToList();
                                if (emplArray.Count > 1)
                                {
                                    UserID = emplArray[1];
                                    EntrustBy = emplArray[0];
                                }
                                else
                                {
                                    UserID = emplArray[0];
                                }
                                // 如果添加用户不在当前正在处理的领导列表中，即可添加，否则直接过滤
                                if (!LeadersHandle.Contains(UserID))
                                {
                                    // 创建正在处理数据
                                    MessageHandle Handle = new Appkiz.Apps.Workflow.Library.MessageHandle();
                                    Handle.ActivatedByNodes = ForwardNodeKey;
                                    Handle.ActivatedReason = 0;
                                    Handle.CreateTime = DateTime.Now;
                                    Handle.EntrustBy = EntrustBy;
                                    Handle.HandleStatus = 0;
                                    Handle.HandleType = 0;
                                    Handle.Memo = string.Empty;
                                    Handle.MessageID = mid;
                                    Handle.NodeKey = LeaderNodeKey;
                                    Handle.NodeName = LeaderNode.NodeName;
                                    Handle.ProcType = 0;
                                    Handle.SendBackThenReturnTo = string.Empty;
                                    Handle.UserID = UserID;

                                    wkfMgr.AddMessageHandle(Handle);
                                    // 更新处理状态
                                    Handle.HandleStatus = 1;
                                    wkfMgr.UpdateMessageHandle(Handle);

                                    //将当前用户添加到修改提醒列表
                                    if (!SenderList.Contains(UserID))
                                    {
                                        SenderList.Add(UserID);
                                    }
                                }
                            }
                            // 更细修改提醒人员列表
                            notifyRecord.Senders = string.Join(",", SenderList);
                            notifyRecord.Receivers = string.Join(",", SenderList);
                            whdb.SaveChanges();

                            return new JsonNetResult(new
                            {
                                Succeed = true,
                                Message = "添加部门指派成功"
                            });
                        }
                    }
                    else
                    {
                        return new JsonNetResult(new
                        {
                            Succeed = false,
                            Message = "当前不允许指定部门"
                        });
                    }
                }
            }
        }
        #endregion

        #region 获得待办已办（修改）列表
        [HttpPost]
        public ActionResult GetChangedRecord(WorkflowQueryInfo query)
        {
            try
            {
                /*
                 * 变量定义
                 */
                // 当前用户
                var employee = (User.Identity as AppkizIdentity).Employee;

                /*
                 * 参数校验
                 */
                // 页数
                if (query.PageNumber <= 0)
                {
                    query.PageNumber = 0;
                }
                if (query.PageSize <= 0)
                {
                    query.PageSize = 10;
                }

                /*
                 * 查询构造
                 */
                var sql = @"SELECT
	                            GW_ReceiveFile.MessageId,
	                            GW_ReceiveFile.ClosedOrHairTime,
	                            GW_ReceiveFile.DocumentNumber,
	                            GW_ReceiveFile.DocumentTitle,
	                            WKF_Message.MessageIssuedBy as InitiateEmplId,
	                            ORG_Employee.EmplName as InitiateEmplName,
	                            WKF_Message.MessageTitle,
	                            WKF_WorkflowHistory.NodeName as MyTask,
	                            WKF_WorkflowHistory.HandledTime as ReceiveTime,
	                            GW_ReceiveFile.SequenceName,
	                            GW_ReceiveFile.SequenceNumber,
	                            GW_ReceiveFile.WorkFlowId
                            FROM 
	                            GW_ReceiveFile
                            join TGR_SendNotifyRecord on
	                            TGR_SendNotifyRecord.AlreadyRead=0 and GW_ReceiveFile.MessageId=TGR_SendNotifyRecord.MessageID and GW_ReceiveFile.DocumentTitle like '%{0}%' and TGR_SendNotifyRecord.EmplID='{1}'
                            join WKF_Message on
	                            WKF_Message.MessageID=GW_ReceiveFile.MessageId
                            join ORG_Employee on
	                            ORG_Employee.EmplID=WKF_Message.MessageIssuedBy
                            join WKF_WorkflowHistory on
	                            WKF_WorkflowHistory.MessageID=WKF_Message.MessageID and WKF_WorkflowHistory.HandledBy = ORG_Employee.EmplID
                            group by
	                            GW_ReceiveFile.MessageId,
	                            GW_ReceiveFile.ClosedOrHairTime,
	                            GW_ReceiveFile.DocumentNumber,
	                            GW_ReceiveFile.DocumentTitle,
	                            WKF_Message.MessageIssuedBy,
	                            ORG_Employee.EmplName,
	                            WKF_Message.MessageTitle,
	                            WKF_WorkflowHistory.NodeName,
	                            WKF_WorkflowHistory.HandledTime,
	                            GW_ReceiveFile.SequenceName,
	                            GW_ReceiveFile.SequenceNumber,
	                            GW_ReceiveFile.WorkFlowId
                            order by 
	                            GW_ReceiveFile.MessageId desc";
                
                var TotalList = DbUtil.ExcuteSqlCommand(string.Format(sql, query.Title, employee.EmplID), DbUtil.WKF_ChangedList);
                List<object> SelectedList = TotalList.Skip(query.PageNumber * query.PageSize).Take(query.PageSize).ToList();
                var totalCount = TotalList.Count();
                // 记录总页数
                var totalPage = (int)Math.Ceiling((float)totalCount / query.PageSize);
                return new JsonNetResult(new
                {
                    Data = SelectedList,
                    TotalInfo = new
                    {
                        TotalPages = totalPage,
                        TotalRecouds = totalCount
                    }
                });
            }
            catch
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "获取错误"
                });
            }
        }
        #endregion

        #region 设置修改已读
        public ActionResult ReadNewOpinion(FormCollection collection)
        {
            /*
             * 参数获取
             */
            // 消息ID
            var mid = collection["mid"];

            /*
             * 参数校验
             */
            // 消息ID
            if(string.IsNullOrEmpty(mid))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "消息ID不能为空"
                });
            }

            /*
             * 设置已读
             */
            List<TGR_SendNotifyRecord> SendRecordList = whdb.SendNotifyRecord.Where(n => n.MessageID == mid && n.AlreadyRead == false).ToList();
            foreach(var record in SendRecordList)
            {
                record.AlreadyRead = true;
            }

            whdb.SaveChanges();
            return new JsonNetResult(new
            {
                Succeed = true,
                Message = "设置已读成功"
            });
        }
        #endregion

        #region 向文电科转发节点发送领导提交/修改通知
        public ActionResult SendLeaderNotify(string mid, string nid, Employee employee)
        {
            try
            {
                /*
                 * 变量定义
                 */
                // 流程管理器
                WorkflowMgr wkfMgr = new WorkflowMgr();

                /*
                 * 参数校验
                 */
                // 获得该流程对应的节点信息
                Dictionary<string, string> nodeDict = WorkflowUtil.GetWorkflowNode(mid);
                if(nodeDict == null)
                {
                    LogService.WriteLog("Tiger", "Message:" + string.Format("Employee:{0},MessageId:{1},NodeKey:{2},Msg:{3}", employee.EmplID, mid, nid, "流程对应节点不存在"), "SendLeaderNotify_Debug", LogService.LogLevel.Debug);

                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "流程对应节点不存在"
                    });
                }
                else
                {
                    // 领导/部门领导的批示会发送通知
                    List<WorkflowHistory> workflowHistoryList = wkfMgr.FindWorkflowHistory(mid, nodeDict["forward"]);
                    if(workflowHistoryList.Count == 0)
                    {
                        LogService.WriteLog("Tiger", "Message:" + string.Format("Employee:{0},MessageId:{1},NodeKey:{2},Msg:{3}", employee.EmplID, mid, nid, "文电科转发未处理"), "SendLeaderNotify_Debug", LogService.LogLevel.Debug);

                        return new JsonNetResult(new
                        {
                            Succeed = false,
                            Message = "文电科转发未处理"
                        });
                    }
                    else
                    {
                        // 通知内容构造
                        Message message = wkfMgr.GetMessage(mid);
                        Dictionary<string, object> dict = new Dictionary<string, object>();

                        dict["type"] = WHConstants.JPush_Workflow_Type;
                        dict["title"] = string.Format("您有新的领导批示通知 \"{0}\"", message.MessageTitle);
                        dict["content"] = new Dictionary<string, object>()
                            {
                                {"mid",  mid}
                            };

                        // 查找文电科转发人员
                        var HandledBy = workflowHistoryList.ElementAt(0).HandledBy;
                        // 文电领导通知人员:该人员可能在拟办，或者在部门承办节点
                        var WendianNotifyList = WorkflowUtil.GetWendianLeaderList(mid, string.Empty, employee.EmplID);
                        // 合并所有通知人员
                        WendianNotifyList.Add(HandledBy);

                        // 循环发送通知
                        foreach(var notifyUser in WendianNotifyList)
                        {
                            // 将领导通知存到数据中，方便文电科查阅
                            using (WhDbContext db = new WhDbContext())
                            {
                                // 意见
                                var opinionDict = new Dictionary<string, string>();
                                // 判断是领导节点，还是部门节点
                                if (nodeDict["leader"] == nid)
                                {
                                    opinionDict = WorkflowUtil.GetLatestOpinion(mid, nid, employee);
                                }
                                else if (nodeDict["dept"] == nid)
                                {
                                    opinionDict = WorkflowUtil.GetDeptLatestOpinion(mid, nid, employee);
                                }
                                else
                                {
                                    LogService.WriteLog("Tiger", "Message:" + string.Format("Employee:{0},MessageId:{1},NodeKey:{2},Msg:{3}", employee.EmplID, mid, nid, "当前节点非领导或部门节点，不发送任何通知"), "SendLeaderNotify_Debug", LogService.LogLevel.Debug);

                                    return new JsonNetResult(new
                                    {
                                        Succeed = false,
                                        Message = "当前节点非领导或部门节点，不发送任何通知"
                                    });
                                }

                                TGR_LeaderOpinion leaderOpinion = new TGR_LeaderOpinion();
                                leaderOpinion.MessageID = mid;
                                leaderOpinion.Sender = employee.EmplID;
                                leaderOpinion.Opinion = opinionDict.Count == 0 ? string.Empty : opinionDict["opinion"];
                                leaderOpinion.Receiver = notifyUser;
                                leaderOpinion.CreateTime = DateTime.Now;
                                leaderOpinion.Checked = false;
                                db.LeaderOpinion.Add(leaderOpinion);
                                db.SaveChanges();
                            }
                            // 发送通知
                            WorkflowUtil.SendLeaderNotification(mid, nid, notifyUser);

                            // 发送极光提醒
                            WorkflowUtil.SendJPushNotification(new List<object>() { notifyUser }, dict);
                        }
                        LogService.WriteLog("Tiger", "Message:" + string.Format("Employee:{0},MessageId:{1},NodeKey:{2},Msg:{3}", employee.EmplID, mid, nid, "发送通知完毕"), "SendLeaderNotify_Debug", LogService.LogLevel.Debug);

                        return new JsonNetResult(new
                        {
                            Succeed = true,
                            Message = "发送通知完毕"
                        });
                    }
                }
            }
            catch(Exception e)
            {
                LogService.WriteLog("Tiger", "Message:" + e.Message, "SendLeaderNotify_Debug", LogService.LogLevel.Debug);

                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = e.Message
                });
            }
        }
        #endregion

        #region 设置文电科已查看，并重定向到详情页面
        public ActionResult LeaderNotifyDetail(string MessageId)
        {
            try
            {
                var employee = (User.Identity as AppkizIdentity).Employee;

                using(WhDbContext db = new WhDbContext())
                {
                    List<TGR_LeaderOpinion> leaderOpinionList = db.LeaderOpinion.Where(n => n.MessageID == MessageId && n.Checked == false && n.Receiver == employee.EmplID).ToList();
                    foreach(TGR_LeaderOpinion opinion in leaderOpinionList)
                    {
                        opinion.Checked = true;
                    }
                    db.SaveChanges();
                    // 重定向到详情页
                    return Redirect(string.Format("/Apps/Workflow/Running/Open?mid={0}", MessageId));
                }
            }
            catch(Exception e)
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = e.Message
                });
            }
        }
        #endregion

        #region 添加收藏
        [HttpPost]
        public ActionResult AddFavorite(FormCollection collection)
        {
            try
            {
                /*
                 * 变量定义
                 */
                // 消息
                WorkflowMgr wkfMgr = new WorkflowMgr();

                /*
                 * 参数获取
                 */
                // 消息ID
                var mid = collection["mid"];
                // 当前用户
                var employee = (User.Identity as AppkizIdentity).Employee;

                /*
                 * 参数校验
                 */
                // 消息ID
                if (string.IsNullOrEmpty(mid))
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "消息ID不能为空"
                    });
                }
                var message = wkfMgr.GetMessage(mid);
                if(message == null)
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "消息不存在"
                    });
                }

                /*
                 * 收藏该条公文
                 */
                // 检查是否已经收藏该条公文
                using(WhDbContext db = new WhDbContext())
                {
                    TGR_FavoriteMessage favorite = db.FavoriteMessage.Where(n => n.MessageID == mid && n.EmplID == employee.EmplID).FirstOrDefault();
                    if(favorite != null)
                    {
                        return new JsonNetResult(new
                        {
                            Succeed = false,
                            Message = "该条公文已收藏"
                        });
                    }
                    else
                    {
                        Doc doc = wkfMgr.GetDocByWorksheetID(wkfMgr.GetDocHelperIdByMessageId(mid));
                        Worksheet worksheet = doc.Worksheet;
                        //收文日期信息
                        var workcellTime = worksheet.GetWorkcell(4, 8);
                        var workcellTimeInfo = workcellTime != null ? workcellTime.WorkcellValue : null;

                        favorite = new TGR_FavoriteMessage();
                        favorite.MessageID = mid;
                        favorite.EmplID = employee.EmplID;
                        //favorite.MessageTime = DateTime.Parse(workcellTimeInfo);
                        favorite.CreateTime = DateTime.Now;

                        db.FavoriteMessage.Add(favorite);
                        db.SaveChanges();

                        return new JsonNetResult(new
                        {
                            Succeed = true,
                            Message = "已收藏"
                        });
                    }
                }
            }
            catch(Exception e)
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = e.Message
                });
            }
        }
        #endregion

        #region 取消收藏公文
        [HttpPost]
        public ActionResult CancelFavorite(FormCollection collection)
        {
            /*
             * 参数获取
             */
            /*
                 * 参数获取
                 */
            // 消息ID
            var mid = collection["mid"];
            // 当前用户
            var employee = (User.Identity as AppkizIdentity).Employee;

            /*
             * 参数校验
             * 不做消息是否存在的检测，防止消息不存在而无法取消收藏
             */
            // 消息ID
            if (string.IsNullOrEmpty(mid))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "消息ID不能为空"
                });
            }

            /*
             * 取消收藏
             */
            using (WhDbContext db = new WhDbContext())
            {
                TGR_FavoriteMessage favorite = db.FavoriteMessage.Where(n => n.MessageID == mid && n.EmplID == employee.EmplID).FirstOrDefault();
                if(favorite == null)
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "此公文未收藏，无法取消"
                    });
                }
                else
                {
                    db.FavoriteMessage.Remove(favorite);
                    db.SaveChanges();

                    return new JsonNetResult(new
                    {
                        Succeed = true,
                        Message = "已取消"
                    });
                }
            }
        }
        #endregion

        #region 获取收藏公文列表
        public ActionResult FavoriteList(FormCollection collection)
        {
            /*
             * 变量定义
             */
            // 分页页数
            int PageNumber = 0;
            // 分页大小
            int PageSize = 10;
            // 获得今年年份
            var Year = DateTime.Now.Year.ToString();
            // 当前用户
            var employee = (User.Identity as AppkizIdentity).Employee;
            // 日期比较sql
            var dateSql = string.Empty;

            /*
             * 参数获取
             */
            // 公文标题
            var Title = collection["Title"];
            // 季度
            //var Quarter = collection["Quarter"];
            // 开始日期
            var StartTime = collection["StartTime"];
            // 结束日期
            var EndTime = collection["EndTime"];
            // 分页页数
            var PageNumberStr = collection["PageNumber"];
            // 分页大小
            var PageSizeStr = collection["PageSize"];

            /*
             * 参数校验
             */
            // 分页页数
            if (!int.TryParse(PageNumberStr, out PageNumber) || PageNumber < 0)
            {
                PageNumber = 0;
            }
            // 分页大小
            if (!int.TryParse(PageSizeStr, out PageSize) || PageSize < 0)
            {
                PageSize = 10;
            }
            // 季度
            if (!string.IsNullOrEmpty(StartTime) && !string.IsNullOrEmpty(EndTime))
            {
                //if (Quarter == WHConstants.First_Quarter)
                //{
                //    StartTime = "1/1";
                //    EndTime = "3/31";
                //}
                //else if(Quarter == WHConstants.Second_Quarter)
                //{
                //    StartTime = "4/1";
                //    EndTime = "6/30";
                //}
                //else if(Quarter == WHConstants.Third_Quarter)
                //{
                //    StartTime = "7/1";
                //    EndTime = "9/30";
                //}
                //else if(Quarter == WHConstants.Fourth_Quarter)
                //{
                //    StartTime = "10/1";
                //    EndTime = "12/31";
                //}
                //else
                //{
                //    return new JsonNetResult(new
                //    {
                //        Succeed = false,
                //        Message = "季度无效"
                //    });
                //}
                dateSql = string.Format(@" WHERE
	                        a.ClosedOrHairTime >= '{0}'
                            AND
	                        a.ClosedOrHairTime <= '{1}'", StartTime, EndTime);
            }

            /*
             * 构造查询语句，查询结果
             */
            var sql = @"SELECT
	                        DISTINCT a.MessageId,
	                        a.ClosedOrHairTime,
	                        a.DocumentNumber,
	                        a.DocumentTitle,
	                        c.MessageIssuedBy as InitiateEmplId,
	                        d.EmplName as InitiateEmplName,
	                        c.MessageTitle,
	                        '' as MyTask,
	                        '' as ReceiveTime,
	                        a.SequenceName,
	                        a.SequenceNumber,
	                        a.WorkFlowId
                        FROM 
	                        GW_ReceiveFile a
                        INNER JOIN TGR_FavoriteMessage b ON
	                        a.MessageId=b.MessageID AND a.DocumentTitle LIKE '%{0}%' AND b.EmplID='{1}'
                        INNER JOIN WKF_Message c ON
	                        c.MessageID=a.MessageId
                        INNER JOIN ORG_Employee d ON
	                        d.EmplID=c.MessageIssuedBy
                        INNER JOIN WKF_WorkflowHistory e ON
	                        e.MessageID=c.MessageID AND e.HandledBy = d.EmplID
                        " + dateSql + @" ORDER BY a.ClosedOrHairTime DESC";
            sql = string.Format(sql, Title, employee.EmplID);
            // 分页Sql
            var paginationSql = sql + string.Format(@" OFFSET {0} ROWS FETCH NEXT {1} ROWS ONLY", PageSize*PageNumber, PageSize);

            List<object> resultList = DbUtil.ExcuteSqlCommand(sql, DbUtil.WKF_FavoriteList).ToList();
            List<object> pageResult = DbUtil.ExcuteSqlCommand(paginationSql, DbUtil.WKF_FavoriteList).ToList();
            //总数
            var totalRecords = resultList.Count();
            //总页数
            var totalPages = totalRecords % PageSize == 0 ? totalRecords / PageSize : totalRecords / PageSize + 1;

            return new JsonNetResult(new
            {
                Data = pageResult,
                TotalInfo = new
                {
                    TotalRecouds = totalRecords,
                    TotalPages = totalPages
                }
            });
        }
        #endregion

        #region 检查公文是否被收藏
        [HttpPost]
        public ActionResult IsFavorite(FormCollection collection)
        {
            try
            {
                /*
                 * 参数获取
                 */
                // 消息ID
                var mid = collection["mid"];
                // 当前用户
                var employee = (User.Identity as AppkizIdentity).Employee;

                /*
                 * 参数校验
                 */
                // 消息ID
                if(string.IsNullOrEmpty(mid))
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "消息ID不能为空"
                    });
                }
                // 
                /*
                 * 获取收藏
                 */
                using (WhDbContext db = new WhDbContext())
                {
                    TGR_FavoriteMessage favoriteMessage = db.FavoriteMessage.Where(n => n.MessageID == mid && n.EmplID == employee.EmplID).FirstOrDefault();

                    return new JsonNetResult(new
                    {
                        Succeed = true,
                        Data = new
                        {
                            isFavorite = (favoriteMessage != null)
                        }
                    });
                }
            }
            catch(Exception e)
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = e.Message
                });
            }
            


        }
        #endregion

        #region 获得拟办意见
        public ActionResult GetNibanOpinion()
        {
            try
            {
                /*
                 * 变量定义
                 */
                var employee = (User.Identity as AppkizIdentity).Employee;
                /*
                 * 参数获取
                 */
                // 消息ID
                var MessageID = Request.Params["MessageID"];

                /*
                 * 参数校验
                 */
                if (string.IsNullOrEmpty(MessageID))
                {
                    return new JsonNetResult(new
                    {
                        Succeed = false,
                        Message = "消息ID不能为空"
                    });
                }

                /*
                 * 获取最新的拟办意见
                 */
                using(var db = new WhDbContext())
                {
                    // 原有的党政办意见
                    WorkflowMgr mgr = new WorkflowMgr();
                    OrgMgr orgMgr = new OrgMgr();
                    Doc doc = mgr.GetDocByWorksheetID(mgr.GetDocHelperIdByMessageId(MessageID));
                    Worksheet worksheet = doc.Worksheet;

                    //党政办签办内容
                    Workcell workcellDZB = worksheet.GetWorkcell(8, 4);
                    string valueDZB = workcellDZB != null ? workcellDZB.WorkcellValue : string.Empty;

                    // 最新意见
                    string latestNibanOpinion = string.Empty;
                    string editIcon = string.Empty;

                    var nibanOpinion = db.NiBanOpinion.Where(n => n.MessageID == MessageID).FirstOrDefault();
                    // 判断是否有编辑标志
                    var nodeDict = WorkflowUtil.GetWorkflowNode(MessageID);
                    if(nodeDict == null)
                    {
                        return new JsonNetResult(new
                        {
                            Succeed = false,
                            Message = "流程对应节点不存在"
                        });
                    }
                    else
                    {
                        List<WorkflowHistory> workflowHistory = mgr.FindWorkflowHistory(MessageID, nodeDict["niban"]);
                        if(workflowHistory.Count == 0)
                        {
                            return new JsonNetResult(new
                            {
                                Succeed = false,
                                Message = "拟办节点未处理"
                            });
                        }
                        else
                        {
                            var HandledBy = workflowHistory.ElementAt(0).HandledBy;
                            if (HandledBy == employee.EmplID)
                            {
                                editIcon = "fa fa-edit";
                            }

                            // 获得最新的意见
                            if (nibanOpinion != null)
                            {
                                latestNibanOpinion = "<div class=\"my-niban-opinion\"><span style =\"word-wrap: break-word;\">" + nibanOpinion.Opinion + "</span><i class=\"" + editIcon + "\" style=\"margin-left:8px\"></i></div>";
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(valueDZB))
                                {
                                    latestNibanOpinion = "<div class=\"my-niban-opinion\"><span style =\"word-wrap: break-word;\">" + valueDZB + "</span><i class=\"" + editIcon + "\" style=\"margin-left:8px\"></i></div>";
                                }
                            }

                            return new JsonNetResult(new
                            {
                                Succeed = true,
                                Opinion = latestNibanOpinion
                            });
                        }
                        
                    }
                }
            }
            catch (Exception e)
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = e.Message
                });
            }
            
        }
        #endregion

        #region 添加拟办意见
        [HttpPost]
        public ActionResult AddNewNibanOpinion(FormCollection collection)
        {
            /*
             * 变量定义
             */
            var employee = (User.Identity as AppkizIdentity).Employee;

            /*
             * 参数获取
             */
            // 消息ID
            var mid = collection["mid"];
            // 意见
            var opinion = collection["opinion"];

            /*
             * 参数校验
             */
            // 消息ID
            if (string.IsNullOrEmpty(mid))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "消息ID不能为空"
                });
            }
            // 意见
            if (string.IsNullOrEmpty(opinion))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "意见不能为空"
                });
            }

            /*
             * 插入新意见
             */
            using (var db = new WhDbContext())
            {
                var nibanOpinion = db.NiBanOpinion.Where(n => n.MessageID == mid && n.EmplID == employee.EmplID).FirstOrDefault();
                if(nibanOpinion == null)
                {
                    nibanOpinion = new TGR_NiBanOpinion();
                    nibanOpinion.MessageID = mid;
                    nibanOpinion.EmplID = employee.EmplID;
                    nibanOpinion.Opinion = opinion;
                    nibanOpinion.CreateTime = DateTime.Now;
                    nibanOpinion.UpdatedTime = DateTime.Now;
                    db.NiBanOpinion.Add(nibanOpinion);
                } else
                {
                    nibanOpinion.Opinion = opinion;
                    nibanOpinion.UpdatedTime = DateTime.Now;
                }
                db.SaveChanges();

                return new JsonNetResult(new
                {
                    Succeed = true,
                    Message = "修改成功"
                });
            }
        }
        #endregion
    }
}